arliss_obsidian/fp/Class/Functor.md
2024-09-22 14:24:51 -05:00

1.1 KiB

What

Typeclasses defining the Functions map, Infix Operators <$>, and <#>.

class Functor f where
  map :: forall a b. (a -> b) -> f a -> f b

Why

Modify the data contained in a Data Structures

Abstracts

  • For 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