User:Duplode/The Reader monad

A game of two halves

 * State is a relatively complicated monad because it threads two things at the same time; namely, the calculations of result value from a state and the updates to that state.
 * Reader is a simplified version of State which only does the result-calculation half of State's job, while working with a static state (the environment).
 * We presented State before Reader because it had more obvious applications. Now, though, it is time to see how its simplified relative can help us.

Definition

 * The definition ins wholly analogous to the one of State, except that the state is not updated or returned by the wrapped function.
 * is analogous to ; there is no function corresponding to , however, as the bind operator does not propagate changes to the environment - thus the name of  , which applies a function to the environment within the reader. (That isn't a problem in most cases, as Reader is tailored exactly for cases in which the State infrequently or never changes.)

What makes it useful?

 * Reader looks a bit boring - just a vanilla function wrapped in a constructor.
 * It, however, is simpler to use than State, which can be worth it if state transitions are inessential to your stateful calculation.
 * Also, there are a number of very practical situations in which some function argument is being used as a static environment: key-value dictionaries, configuration settings, fixed parameters for a model, strategy-pattern functions, etc. Passing this kind of stuff around as argument to every other function gets annoying quickly. Reeader provides a way to combine functions acting on a shared environment in a single computation, and thus removing boilerplate.

Automotive example

 * Using a CarModel environment (with a torque curve, gear ratios and whatever else you want) to compute, from an rpm value, stuff such as effective torque and power curves for each gear, predicted speeds at some rpm/gear state, aerodynamic drag, top speed, etc.
 * The Reader monad as a fancy way of doing function composition. Show that in a way other monads were also like that, except that there were other details obscuring the view.
 * Rhetorical question (posed as an exercise): How far we are from an actual drag racing simulator? (A: not much - all it is necessary is to switch the computations to the State monad so that changeable state like current speed and time can evolve).

Transformers

 * Quick initial considerations, then go hands on.
 * Maybe for robustness, and also for making some things in CarModel less awkward (e.g., getting gear ratios from a map rather than from a partial function).
 * Exercises (in the form "suggest how transformers could help with...")
 * ReaderT Reader for toy comparison of two cars.
 * StateT Reader for separation of concerns in implementing the simulation - StateT CarModel (Reader CarParameters) a.