Monad.State

Like Monad.Reader, the state monad can share an environment between different operations. Additionally, it can store an arbitrary value.

Example

iex> use Monad.Operators
iex> env = %{dev: %{url: "http://www.example.com/dev"}, prod: %{url: "https://www.example.com/prod"}}
iex> s = state(&{env, &1})
...> ~>> (fn x -> state(&{x[&1], &1}) end)
...> ~>> (fn x -> state(&{x[:url], &1}) end)
...> ~>> (fn x -> state(&{x <> "/index.html", &1}) end)
iex> fun = runState s
iex> fun.(:dev)
{"http://www.example.com/dev/index.html", :dev}
iex> fun.(:prod)
{"https://www.example.com/prod/index.html", :prod}

iex> import Curry
iex> state = curry(& &1 + &2) <|> state(& {5, &1 * 2}) <~> state(& {9, &1 * &1})
iex> fun = runState state
iex> fun.(2)
{14, 16}
iex> fun.(-12)
{14, 576}
Source

Summary

bind(state_monad, fun)

Callback implementation of Monad.Behaviour.bind/2

return(value)

Callback implementation of Monad.Behaviour.return/1

runState(state)

Returns the function wrapped in the state monad

state(fun)

Wraps fun in a state monad

Types

t

Functions

bind(state_monad, fun)

Specs:

  • bind(t, (term -> t)) :: t

Callback implementation of Monad.Behaviour.bind/2.

iex> s1 = state &{&1 <> "!", &1}
iex> s2 = bind(s1, fn x -> state(fn s -> {x <> "?", s} end) end)
iex> fun = runState s2
iex> fun.("State")
{"State!?", "State"}
Source
return(value)

Specs:

  • return(term) :: t

Callback implementation of Monad.Behaviour.return/1.

Converts value into function that takes some state and returns the value as-is and the state. Then the function is wrapped into a state monad.

iex> s = return 42
iex> fun = runState s
iex> fun.("My state")
{42, "My state"}
Source
runState(state)

Specs:

  • runState(t) :: (term -> {term, term})

Returns the function wrapped in the state monad.

iex> s = state &{&1 * 2, "Doubled"}
iex> fun = runState s
iex> fun.(42)
{84, "Doubled"}
Source
state(fun)

Specs:

  • state((term -> {term, term})) :: t

Wraps fun in a state monad.

iex> s = state &{&1 * 2, "Doubled"}
iex> s.fun.(42)
{84, "Doubled"}
Source