I am trying to write a monad for discrete random variables in haskell. The type class looks something like this:
{- LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
class (Num w, Monad m) => MonadDiscrete w m where
sample :: [(a, w)] -> m a
I'd like to make two instances of this. The first is like the list monad:
newtype Discrete w a = Discrete [(a, w)]
instance (Num w) => Monad (Discrete w) where
...
instance (Num w) => MonadDiscrete w (Discrete w) where
sample = Discrete
The second is using the PRNG in MonadRandom:
instance (MonadRandom m) => MonadDiscrete Rational m where
sample = fromList
However, if I try to do something like:
x :: (Num w, MonadDiscrete w m) => m String
x = sample [("x", 1)]
GHC gives me an error:
Could not deduce (MonadDiscrete w0 m) arising from the ambiguity check for
it' from the context (MonadDiscrete w m) bound by the inferred type for
it': MonadDiscrete w m => m [Char] at :7:1-17 The type variablew0' is ambiguous Possible fix: add a type signature that fixes these type variable(s) Note: there are several potential instances: instance Num w => MonadDiscrete w (Discrete w) -- Defined at lib/Discrete.hs:64:10 instance Control.Monad.Random.Class.MonadRandom m => MonadDiscrete Rational m -- Defined at lib/Discrete.hs:58:10 When checking that
it' has the inferred type `forall w (m :: * -> *). MonadDiscrete w m => m [Char]' Probable cause: the inferred type is ambiguous
I've tried all sorts of things including adding FunDeps or making w an associated type, but all fail.
MonadDiscrete (Discrete w)
needs another type parameter... That said, have you tried disambiguating the constant1
inx
, like so:(1::Int)
? – yatima2975FunctionalDependencies
. – Cactus