无法从 (MonadRandom r) 推导出 (Functor r)
下面的简单代码
import Control.Monad
import Control.Monad.Random
psum :: (MonadRandom r) => Int -> r Double -> r Double
psum n x = fmap sum $ replicateM n x
会产生错误:
Could not deduce (Functor r) arising from a use of `fmap'
from the context (MonadRandom r)
这对我来说很奇怪,因为
class (Monad m) => MonadRandom m where ...
在 Control.Monad.Random.Class
源文件中,并且由于 monads 是函子,GHC 应该推断出 r 在我的上下文中是一个函子。我还尝试导入
Control.Monad.Random.Class
但没有成功。
手动添加 r
上的 Functor
约束是可行的,但我发现这很丑陋。
我在这里缺少什么?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
理论上,Monad 是函子,但遗憾的是,Functor 并不是
Monad
的超类,没有什么充分的理由。您还可以使用
liftM
代替fmap
,而不是添加Functor r
。编辑:似乎确实没有充分的理由。这些类在 Haskell 1.3 中一起引入,并且超类已经存在并用于
MonadPlus
和MonadZero
。Theoretically monads are functors, but sadly
Functor
is not a superclass ofMonad
for no good reason.Instead of adding
Functor r
you can also useliftM
instead offmap
.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
andMonadZero
.