The Reader Monad¶
- members:
Reader, asks, local, lookup, reader, reader_m
- class hymn.types.reader.Reader¶
the reader monad
computations which read values from a shared environment
- classmethod unit(cls, value)¶
the unit of reader monad
- local(self, f)¶
return a reader that execute computation in modified environment
- run(self, e)¶
run the reader and extract the final vaule
- hymn.types.reader.asks(f)¶
- hymn.types.reader.reader(f)¶
create a simple reader action from
f
- hymn.types.reader.local(f)¶
executes a computation in a modified environment,
f :: e -> e
- hymn.types.reader.lookup(key)¶
create a lookup reader of
key
in the environment
- hymn.types.reader.ask¶
fetch the value of the environment
Hy Specific API¶
- reader-m
alias of
Reader
- <-
alias of
lookup()
Examples¶
Do Notation¶
=> (import hymn.types.reader [ask])
=> (require hymn.macros [do-monad-return])
=> (.run (do-monad-return [e ask] (+ e 1)) 41)
42
Operations¶
asks()
creates a reader with a function, reader()
is an alias of
asks()
=> (import hymn.types.reader [asks reader])
=> (require hymn.macros [do-monad-return])
=> (defn first [c] (get c 0))
=> (defn second [c] (get c 1))
=> (.run (do-monad-return [h (asks first)] h) [5 4 3 2 1])
5
=> (.run (do-monad-return [h (reader second)] h) [5 4 3 2 1])
4
Use ask()
to fetch the environment
=> (import hymn.types.reader [ask])
=> (.run ask 42)
42
=> (require hymn.macros [do-monad-return])
=> (.run (do-monad-return [e ask] (+ e 1)) 42)
43
local()
runs the reader with modified environment
=> (import hymn.types.reader [ask local])
=> (.run ask 42)
42
=> (.run ((local (fn [x] (+ x 1))) ask) 42)
43
Use lookup()
to get the value of key in environment, <-
is an
alias of lookup()
=> (import hymn.types.reader [lookup <-])
=> (.run (lookup 1) [1 2 3])
2
=> (.run (lookup 'b) {'a 1 'b 2})
2
=> (.run (<- 1) [1 2 3])
2
=> (.run (<- 'b) {'a 1 'b 2})
2
=> (require hymn.macros [do-monad-return])
=> (.run (do-monad-return [a (<- 'a) b (<- 'b)] (+ a b)) {'a 25 'b 17})
42