2011-10-23 30 views
4

簡單下面的代碼無法推斷出(MonadRandom R)

import Control.Monad 
import Control.Monad.Random 

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

(函子R)產生了錯誤:

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

這是怪我,因爲

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

in Control.Monad.Random.Class源文件,並且由於monads是仿函數,因此GHC應該推斷r是af在我的情況下,unctor。我也嘗試導入Control.Monad.Random.Class沒有成功。

r上手動添加Functor約束的作品,但我覺得這很難看。

我在這裏錯過了什麼?

回答

9

理論上monad是仿函數,但遺憾的是Functor不是Monad的超類,沒有很好的理由。

而不是添加Functor r您還可以使用liftM而不是fmap

編輯:真的好像沒有什麼好的理由。這些課程在Haskell 1.3中一起介紹,並且超類已經存在並用於MonadPlusMonadZero

+2

啊哈。我正在做太多的數學。謝謝你,先生。 –