[[Typeclasses|Typeclass]] defining the [[Functions|function]] `map`, [[Infix Operators|operators]] `<$>`, and `<#>`. ```haskell class Functor f where map :: forall a b. (a -> b) -> f a -> f b ``` ## map For a [[Data Structures|data structure]] 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` to `f a -> f b`: > ```haskell > addTwo :: Int -> Int > addTwo = add 2 > > maybeAddTwo :: Maybe Int -> Maybe Int > maybeAddTwo = map addTwo > ``` Replaces the patterns: - Modify every element in [[Collections|collection]] ... - When [[Maybe|nullable]] value is non-null ... - When _(potentially async)_ [[Effect|IO]] resolves ... ## Examples ### [[Array]] of [[Int]] ```haskell add 1 <$> [1, 2, 3] -- [2, 3, 4] ``` ### [[Maybe]] of [[Int]] ```haskell add 1 <$> Just 1 -- Just add 1 <$> Nothing -- Nothing ``` ### [[Effect]] of [[Int]] See also: - [[Bind]] - [[Show]] - [[Functions/Composition|compose]] - [[do notation]] ```haskell 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 ```