【发布时间】:2014-11-12 06:21:16
【问题描述】:
我正在尝试在 haskell 中为离散随机变量编写一个 monad。类型类看起来像这样:
{- LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
class (Num w, Monad m) => MonadDiscrete w m where
sample :: [(a, w)] -> m a
我想为此做两个实例。第一个就像 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
第二个是在 MonadRandom 中使用 PRNG:
instance (MonadRandom m) => MonadDiscrete Rational m where
sample = fromList
但是,如果我尝试执行以下操作:
x :: (Num w, MonadDiscrete w m) => m String
x = sample [("x", 1)]
GHC 给我一个错误:
无法推断 (MonadDiscrete w0 m) 由
it' from the context (MonadDiscrete w m) bound by the inferred type forit' 的歧义检查引起:MonadDiscrete w m => m [Char] 在:7:1-17 类型变量w0' 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 thatit' 具有推断类型`forall w (m :: * -> *)。 MonadDiscrete w m => m [字符]' 可能原因:推断类型不明确
我尝试了各种方法,包括添加 FunDeps 或使 w 成为关联类型,但都失败了。
【问题讨论】:
-
你能修复你的代码示例吗?
MonadDiscrete (Discrete w)的实例需要另一个类型参数...也就是说,您是否尝试过消除x中的常量1的歧义,例如:(1::Int)? -
答案将是
FunctionalDependencies。