[Haskell-beginners] Guard in class def

Chaddaï Fouché chaddai.fouche at gmail.com
Sun Jan 8 12:44:43 CET 2012


On Sun, Jan 8, 2012 at 10:29 AM, Henry Lockyer
<henry.lockyer at ntlworld.com> wrote:
> Hi,
> I was just looking through the 'Monad Transformers' chapter in Real World Haskell. They are using the "reader" monad to illustrate the transformer structure  but I fell off at the first bend when I saw the following:
>
> class (Monad m) => MonadReader r m | m -> r where
>  ask     :: m r
>  local  :: (r -> r) -> m a -> m a
>
> Could someone explain the use of a guard here / how to read this with the "| m -> r"  ?
> I haven't come across this usage before (as far as I have noticed :-) and the meaning hasn't jumped out at me yet...

It's not a "guard", it's a functional dependency : "m -> r" tells the
compiler that for any m, r is uniquely determined. That is if you have
the monad "ReaderT Int Identity" for m, it is clear that "Int" is the
only possibility for r.
This is necessary for type inference to process in more case (often
the type of the monad is fixed by the context, but not the type of r,
thanks to the FD, the compiler can confidently use the instance it
found for m).

Note that this solution never really satisfied the Haskell
users/developers since it is more from the logic paradigm (like
Prolog) than the functional paradigm, so since two or three years now,
this tends to be replaced by a new solution, more functional in style,
called type family, which would read like that :

> class (Monad m) => MonadReader m where
>    type RC :: * -> * -- Reader content
>    ask     :: m (RC m)
>    local  :: (RC m -> RC m) -> m a -> m a

where RC is like a "function on type".

-- 
Jedaï



More information about the Beginners mailing list