Tuesday, April 13, 2010

[lgyaaiqo] Haskell's (->) r is the reader monad

The bizarre syntax "(->) r" described in the Control.Monad.Instances is the Reader monad "in disguise" or without English accessors.  In more normal infix notation, it looks like "r -> ___", meaning it is a typeclass of functions all of which take one argument of type r.  With currying, the functions can take many arguments; the first input argument must be of type r.  Interpret that argument as a static environment, so the monad is a state monad whose state (of type r) may only be read, not written to.

With "do" notation, one can lexically bind with "<-", like with "let", without having to specify the environment on the right hand side.  Outside of do notation, one can compose, with ">>=", a sequence of type compatible functions without having to specify the environment for each function call.  The functions go in natural order unlike compose (.) which requires them in reverse order.

The "ask" function is "id".  runReader is simply calling the expression as a function, giving the environment as a parameter.

The Functor instance does the obvious thing, altering the output from a to b using the function provided to fmap.

It was difficult to find information about this monad because one cannot search for just the symbol ->, and it doesn't seem to have a name.  I finally found my satisfying answer in Yorgey's Typeclassopedia article.

Here are some unsuccessful search queries I tried:

  • Currying monad
  • Function monad
  • Partial function monad
  • Function application monad
  • Function partial application monad
  • Arrow monad

No comments :