std:State
lib/State.omg
lib/State.omg55 lines
1{- The state monad: computations that read and update a state of type `s`.
2
3 A `State s a` is a function from the current state to a result and the
4 new state. The state and the result can be of any universe, each its
5 own. A monad has a single universe, though: `monad s` is the monad of
6 the computations whose results are in the universe of the state, which
7 is why `put` and `modify` produce `unit @l`, the empty record type of
8 that universe.
9-}
10
11let monads = std:Monad
12
13let State
14 : forall {ls la : Level} -> Type ls -> Type la -> Type (Level/max ls la)
15 = \s a -> s -> a * s
16
17let pure
18 : forall {ls la : Level} {s : Type ls} {a : Type la} -> a -> State s a
19 = \x state -> (x, state)
20
21let bind
22 : forall {ls la lb : Level} {s : Type ls} {a : Type la} {b : Type lb}
23 -> State s a
24 -> (a -> State s b)
25 -> State s b
26 = \m f state ->
27 let step = m state
28 in f step.1 step.2
29
30let get : forall {l : Level} {s : Type l} -> State s s = \state -> (state, state)
31
32let put : forall {l : Level} {s : Type l} -> s -> State s (unit @l) = \new _ -> ({=}, new)
33
34let modify
35 : forall {l : Level} {s : Type l} -> (s -> s) -> State s (unit @l)
36 = \f state -> ({=}, f state)
37
38-- Run a computation from an initial state: the result and the final state.
39let run
40 : forall {ls la : Level} {s : Type ls} {a : Type la} -> State s a -> s -> a * s
41 = \m state -> m state
42
43let eval
44 : forall {ls la : Level} {s : Type ls} {a : Type la} -> State s a -> s -> a
45 = \m state -> (m state).1
46
47let exec
48 : forall {ls la : Level} {s : Type ls} {a : Type la} -> State s a -> s -> s
49 = \m state -> (m state).2
50
51-- The functions `pure` and `bind` above, for results in the universe of the
52-- state.
53let monad : forall {l : Level} (s : Type l) -> monads.Monad @l (State s) = \s -> { pure, bind }
54
55in { State, pure, bind, get, put, modify, run, eval, exec, monad }