Update
This commit is contained in:
parent
a97447840e
commit
0660fe3b1d
1 changed files with 32 additions and 2 deletions
34
monad.md
34
monad.md
|
@ -12,7 +12,37 @@ A typical example is a **maybe** monad which wraps a type such as integer to han
|
|||
2. A special function *return(X)* that converts value of given type into this maybe type, e.g. *return(3)* will return *just(3)*
|
||||
3. A special combinator *X >>= f* which takes a monadic (*maybe*) values *X* and a function *f* and does the following:
|
||||
- if *X* is *nothing*, gives back *nothing*
|
||||
- if *X* is a value *just(N)*, gives back the value *f(N)*
|
||||
- if *X* is a value *just(N)*, gives back the value *f(N)* (i.e. unwraps the value and hand it over to the function)
|
||||
|
||||
Let's look at a pseudocode example of writing a safe division function. Without using the combinator it's kind of ugly:
|
||||
|
||||
TODO: example in some lang, e.g. haskell
|
||||
```
|
||||
divSafe(x,y) = // takes two maybe values, returns a maybe value
|
||||
if x == nothing
|
||||
nothing else
|
||||
if y == nothing
|
||||
nothing else
|
||||
if y == 0
|
||||
nothing else
|
||||
just(x / y)
|
||||
```
|
||||
|
||||
With the combinator it gets much nicer (note the use of [lambda expression](lambda.md)):
|
||||
|
||||
```
|
||||
divSafe(x,y) =
|
||||
x >>= { a: y >== { b: if b == 0 nothing else a / b } }
|
||||
```
|
||||
|
||||
Languages will typicall make this even nicer with a [syntax sugar](syntax_sugar.md) such as:
|
||||
|
||||
```
|
||||
divSafe(x,y) = do
|
||||
a <- x,
|
||||
b <- y,
|
||||
if y == 0 nothing else return(a / b)
|
||||
```
|
||||
|
||||
TODO: I/O monad
|
||||
TODO: general monad
|
||||
TODO: example in real lang, e.g. haskell
|
||||
|
|
Loading…
Reference in a new issue