Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not deduce (Functor r) from (MonadRandom r)

Tags:

haskell

The simple following code

import Control.Monad
import Control.Monad.Random

psum :: (MonadRandom r) => Int -> r Double -> r Double
psum n x = fmap sum $ replicateM n x

yields the error:

Could not deduce (Functor r) arising from a use of `fmap'
    from the context (MonadRandom r)

This is weird to me because of

class (Monad m) => MonadRandom m where ...

in Control.Monad.Random.Class source file, and since monads are functors, GHC should have deduced that r is a functor in my context. I also tried to import Control.Monad.Random.Class with no success.

Adding manually the Functor constraint on r works, but I find this quite ugly.

What am I missing here ?

like image 309
Alexandre C. Avatar asked Jan 18 '23 10:01

Alexandre C.


1 Answers

Theoretically monads are functors, but sadly Functor is not a superclass of Monad for no good reason.

Instead of adding Functor r you can also use liftM instead of fmap.

Edit: There really seems to be no good reason. The classes were introduced together in Haskell 1.3, and superclasses already existed and were used for MonadPlus and MonadZero.

like image 98
Sjoerd Visscher Avatar answered Jan 20 '23 23:01

Sjoerd Visscher