forked from orion/obsidian
1.4 KiB
1.4 KiB
Typeclasses defining the Functions map
, Infix Operators <$>
, and <#>
.
class Functor f where
map :: forall a b. (a -> b) -> f a -> f b
map
For a Data Structures containing some data a
, change the data using some function a -> b
.
[!info] Another way of thinking of map is that it lifts a function of
a -> b
tof a -> f b
:addTwo :: Int -> Int addTwo = add 2 maybeAddTwo :: Maybe Int -> Maybe Int maybeAddTwo = map addTwo
Replaces the patterns:
- Modify every element in Collections ...
- When Maybe value is non-null ...
- When (potentially async) Effect resolves ...
Examples
Array of Int
add 1 <$> [1, 2, 3]
-- [2, 3, 4]
Maybe of Int
add 1 <$> Just 1
-- Just
add 1 <$> Nothing
-- Nothing
Effect of Int
See also:
import Node.FS.Sync (readTextFile, writeTextFile)
import Node.Encoding (Encoding(..))
import Data.Int as Int
writeNum :: Int -> Effect Unit
writeNum n = writeTextFile "num.txt" (show n) UTF8
readNum :: Effect Int
readNum =
readTextFile "num.txt" UTF8
>>= (Int.fromString >>> liftMaybe (error "invalid integer"))
main = do
writeNum
n <- add 1 <$> readNum
log $ show n
-- 2