事实证明,在GHC 7.10中,编译很好:
mysum xs = foldr (+) 0 xs
但是这个:
mysum = foldr (+) 0
导致以下错误:
No instance for (Foldable t0) arising from a use of ‘foldr’
The type variable ‘t0’ is ambiguous
Relevant bindings include
mysum :: t0 Integer -> Integer (bound at src/Main.hs:37:1)
Note: there are several potential instances:
instance Foldable (Either a) -- Defined in ‘Data.Foldable’
instance Foldable Data.Functor.Identity.Identity
-- Defined in ‘Data.Functor.Identity’
instance Foldable Data.Proxy.Proxy -- Defined in ‘Data.Foldable’
...plus five others
In the expression: foldr (+) 0
In an equation for ‘mysum’: mysum = foldr (+) 0
为什么会发生这种情况,以及通过了解这种差异所获得的洞察力是什么?另外,我可以给这个函数一个类型(那仍然是通用的)以使这个错误消失吗?
答案 0 :(得分:13)
与正常情况一样,如果使用无类型的良好类型函数突然导致类型错误导致未实现的类型类约束,最终的原因是monomorphism restriction,默认情况下启用。
您可以通过向mysum
添加类型签名来解决此问题:
mysum :: (Foldable f, Num a) => f a -> a
或通过关闭单态限制:
{-# LANGUAGE NoMonomorphismRestriction #-}