monads
examples/monads.omg
examples/monads.omg56 lines
1{- Monads and `do` blocks.
2
3 omegyu normalize examples/monads.omg
4
5 A monad is a record of two functions, `pure` and `bind`. A `do` block
6 names the record it uses; without one, it is in the builtin `IO` monad.
7-}
8
9let Monad = std:Monad
10
11let State = std:State
12
13-- Division that fails instead of dividing by zero.
14let divide
15 : Natural -> Natural -> Optional Natural
16 = \a b -> if Natural/isZero b then None Natural else Some (Natural/div a b)
17
18-- In the `Optional` monad, the first failure ends the computation.
19let average
20 : Natural -> Natural -> Optional Natural
21 = \total count ->
22 do Monad.optional {
23 mean <- divide total count;
24 Some (mean + 1)
25 }
26
27-- In the `List` monad, every combination is tried.
28let pairs
29 : List (Natural * Text)
30 = do Monad.list {
31 n <- [ 1, 2 ];
32 s <- [ "a", "b" ];
33 [ (n, s) ]
34 }
35
36-- In a state monad, a counter is threaded through the computation.
37let counter = State.monad Natural
38
39let tick
40 : State.State Natural Natural
41 = do counter { n <- State.get; State.put (n + 1); State.pure n }
42
43let threeTicks
44 : State.State Natural (List Natural)
45 = do counter {
46 a <- tick;
47 b <- tick;
48 c <- tick;
49 State.pure [ a, b, c ]
50 }
51
52in { ok = average 10 2
53 , failed = average 10 0
54 , pairs
55 , ticks = State.run threeTicks 10
56 }