The Reader Monad

class hymn.types.reader.Reader(value)

Bases: hymn.types.monad.Monad

the reader monad

computations which read values from a shared environment

bind(f)

the bind operation of Reader

local(f)

return a reader that execute computation in modified environment

run(e)

run the reader and extract the final vaule

classmethod unit(value)

the unit of reader monad

hymn.types.reader.asks(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.reader(f)

create a simple reader action from f

hymn.types.reader.reader_m

alias of Reader

hymn.types.reader.unit()

alias of Reader.unit()

hymn.types.reader.run()

alias of Reader.run()

hymn.types.reader.ask

fetch the value of the environment

Hy Specific API

reader-m

alias of Reader

Function

<-

alias of lookup()

Examples

Do Notation

=> (import [hymn.types.reader [ask]])
=> (require [hymn.macros [do-monad]])
=> (.run (do-monad [e ask] (inc e)) 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]])
=> (.run (do-monad [h (asks first)] h) [5 4 3 2 1])
5
=> (.run (do-monad [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]])
=> (.run (do-monad [e ask] (inc e)) 42)
43

local() runs the reader with modified environment

=> (import [hymn.types.reader [ask local]])
=> (.run ask 42)
42
=> (.run ((local inc) 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]])
=> (.run (do-monad [a (<- 'a) b (<- 'b)] (+ a b)) {'a 25 'b 17})
42