state.md

December 15, 2024 ยท View on GitHub

State

State is parameterized by two types: a state <code>s</code> and a result <code>a</code>.
State should wrap a function of the form <code>s -> Pair a s</code> and can be constructed by providing a function of this form. There are three methods available on the State for running with a given initial state.

Implements: Monad

State(f)

The State constructor.

ParamTypeDescription
ffunctionA function of the form s -> Pair a that is wrapped by the State. Nothing is executed until it is run with an initial state s.

State.of(v)

The State constructor that populates the right portion with its argument. of essentially lifts a value of type a into a State.

ParamTypeDescription
vanyAny value that needs to be lifted into the State

State.toString()

Gets a stringified version of the State.

State.map(f)

Applies the function f to the right portion of the State.

ParamTypeDescription
ffunctionFunction

State.getValue()

Gets the function within the State.

State.ap(t)

ap allows for values wrapped in a State to be applied to functions also wrapped in a State. In order to use ap, the State must contain a function as its value on the right side.

ParamTypeDescription
tStateA State with a function as its right element

State.chain(f)

Chains together many computations that return a State.

ParamTypeDescription
ffunctionFunction that returns another State

State.runWith(s)

Since State is a lazy datatype that requires an initial state to run, it provides a runWith method that takes in an initial state and returns the result of the computation as a <code>Pair result state</code>.

ParamTypeDescription
sanyAn initial state that needs to be passed to the State

State.execWith(s)

When called, execWith will run the state transition with the given value as the initial state and return the state.

ParamTypeDescription
sanyAn initial state that needs to be passed to the State

State.evalWith(s)

When called, evalWith will run the state transition with the given value as the initial state and return the result.

ParamTypeDescription
sanyAn initial state that needs to be passed to the State