forked from orion/obsidian
57 lines
1.1 KiB
Markdown
57 lines
1.1 KiB
Markdown
|
## What
|
||
|
[[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
|
||
|
```
|
||
|
|
||
|
## Why
|
||
|
Modify the data contained in a [[Data Structures|data structure]]
|
||
|
|
||
|
### Abstracts
|
||
|
- For 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]]
|
||
|
- [[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
|
||
|
```
|