transformers

Matt Bierner edited this page Nov 19, 2015 · 7 revisions

Akh monad transformers are functions that take a monad and return a new monad.

General Transformer Interface

M.inner

The type of the inner monad passed to the transformer.

const M = StateT(List);
M.inner === List;

const M = ErrorT(StateT(List));
M.inner === StateT (List);
M.inner.inner === List;

M.lift()

Lift an operation from the inner monad so that it can be performed in the transformed monad.

const M = ErrorT(State);

// To read/write the state
M.lift(State.get);
M.lift(M.inner.get); 

// Adding operations to transformed monad
M.get = M.lift(State.get);
M.modify = (f) => M.lift(M.inner.modify(f)); 

Lift can be used on both the type and instances.

// These are the same
M.lift(...);
M.of(2).lift(...); // note that this effectively discards the instance 

M.liftInner()

When dealing with a larger stack of monad transformers, lifting though multiple levels with lift can be tedious. liftInner lifts from inner monad transformers without referencing them directly.

const M = ErrorT(StateT(StateT(State)));

// To read/write the first state.
M.lift(M.inner.get); 

// To read/write the middle state
M.liftInner(M.inner.get);

// To read/write the innermost state.
// `liftInner` can be chained 
M.liftInner.liftInner(M.inner.inner.get);

Automatic State Lifting

All builtin Akh monad transformers automatically try to lift state operations from the first State monad in the stack. Any nested state computations must be manually lifted.

const M = ErrorT(StateT(StateT(State)));

// This is automatically lifted from the first state. 
M.get(); 

// Middle state computations must be manually lifted.
M.liftInner(M.inner.get);

// To read/write the innermost state.
// `liftInner` can be chained 
M.liftInner.liftInner(M.inner.inner.get);
Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.