At different questions I’ve found hints in comments concerning using the (->) instance of Monads e.g. for realizing point-free style.
As for me, this is a little too abstract. Ok, I’ve seen Arrow instances on (->) and it seems to me, that (->) can be used in instance notations but not in type declarations (that would alone be stuff for another question).
Has anyone examples using (->) as instance of Monad? Or a good link?
Sorry if this question may already have been discussed here, but searching for “(->) Monad instance” gives you many many hits as you can imagine … since nearly every question about Haskell somewhere involves (->) or “Monad”.
For a given type
r, the function of typer -> acan be thought of as a computation delivering anausing an environment typedr. Given two functionsr -> aanda -> (r -> b), it’s easy to imagine that one can compose these when given an environment (again, of typer).But wait! That’s exactly what monads are about!
So we can create an instance of Monad for
(->) rthat implementsf >>= gby passing therto bothfandg. This is what the Monad instance for(->) rdoes.To actually access the environment, you can use
id :: r -> r, which you can now think of as a computation running in an environmentrand delivering anr. To create local sub-environments, you can use the following:This pattern of having an environment passed to computations that can then query it and modify it locally is useful for not just the
(->) rmonad, which is why it is abstracted into theMonadReaderclass, using much more sensible names than what I’ve used here:http://hackage.haskell.org/packages/archive/mtl/2.0.1.0/doc/html/Control-Monad-Reader-Class.html
Basically, it has two instances:
(->) rthat we’ve seen here, andReaderT r m, which is just anewtypewrapper aroundr -> m a, so it’s the same thing as the(->) rmonad I’ve described here, except it delivers computations in some other, transformed monad.