我試圖用foldr實現filterM函數,但接收到一個我不明白爲什麼的錯誤。我不明白爲什麼不能Haskell推斷這種類型
我的實現(它只是爲了解,我知道我應該使用做記號...):
filterM :: (Monad m) => (a -> (m Bool)) -> [a] -> m [a]
filterM f list = foldr foldFn (return []) list
where
foldFn :: (Monad m) => a -> m [a] -> m [a]
foldFn x acc = let
m = f x
in acc >>=
\l -> m >>=
\b -> (if b == True then return (x:l) else return l)
我收到以下錯誤
Could not deduce (a ~ a1)
from the context (Monad m)
bound by the type signature for
filterM :: Monad m => (a -> m Bool) -> [a] -> m [a]
at wadler.hs:124:12-55
or from (Monad m1)
bound by the type signature for
ff :: Monad m1 => a1 -> m1 [a1] -> m1 [a1]
at wadler.hs:127:23-54
`a' is a rigid type variable bound by
the type signature for
filterM :: Monad m => (a -> m Bool) -> [a] -> m [a]
at wadler.hs:124:12
`a1' is a rigid type variable bound by
the type signature for ff :: Monad m1 => a1 -> m1 [a1] -> m1 [a1]
at wadler.hs:127:23
In the first argument of `f', namely `x'
In the expression: f x
In an equation for `m': m = f x
我不知道爲什麼鍵入一個不能推導出因爲foldr相似的類型是預先foldr :: (a -> b -> b) -> b -> [a] -> b
謝謝, 亞歷
您確定這是正確的代碼嗎?我沒有範圍內的'xs'。 – bheklilr 2014-09-24 15:16:02
如果使用由外部模式引入的變量,則不應將類型簽名添加到本地函數。如果你想這樣做,你必須*使用'ScopedTypeVariables'擴展名並量化外簽名中的變量。 – Bakuriu 2014-09-24 15:26:45