如何让MonadRandom成为Functor?

时间:2014-09-02 11:41:48

标签: haskell monads

似乎来自random-fu包的MonadRandom不是Functor,因为我收到的错误如下:

Could not deduce (Functor m) arising from a use of ‘_1’
from the context (MonadRandom m)

我尝试添加以下代码:

instance Functor MonadRandom where
    fmap = liftM

instance Applicative MonadRandom where
    pure  = return
    (<*>) = ap

但是我收到了错误:

The first argument of ‘Functor’ should have kind ‘* -> *’,
  but ‘MonadRandom’ has kind ‘(* -> *) -> Constraint’
In the instance declaration for ‘Functor MonadRandom’

The first argument of ‘Applicative’ should have kind ‘* -> *’,
  but ‘MonadRandom’ has kind ‘(* -> *) -> Constraint’
In the instance declaration for ‘Applicative MonadRandom’

1 个答案:

答案 0 :(得分:17)

MonadRandom是一个类,而不是类型为* -> *的类型,例如Maybe。通常,你会使用像

这样的东西
instance MonadRandom m => Functor m where
    fmap = liftM

instance MonadRandom m => Applicative m where
    pure  = return
    (<*>) = ap

然而,在这种情况下instances of MonadRandom已经是仿函数,所以现在实例不明确!相反,您应该在函数中添加Functor约束:

yourFunction :: (MonadRandom m, Functor m) => ...
-- instead of yourFunction :: (MonadRandom m) => ...