为什么Haskell指向函数的自由版本导致模糊类型错误?

Ana*_*Ana 10 haskell types function monomorphism-restriction

事实证明,在GHC 7.10中,这编译很好:

mysum xs = foldr (+) 0 xs
Run Code Online (Sandbox Code Playgroud)

但是这个:

mysum    = foldr (+) 0
Run Code Online (Sandbox Code Playgroud)

导致以下错误:

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
Run Code Online (Sandbox Code Playgroud)

为什么会发生这种情况,通过了解这种差异可以获得什么?另外,我可以给这个函数一个类型(仍然是通用的)来使这个错误消失吗?

Cac*_*tus 13

像往常一样,如果使得一个良好类型的函数无点突然导致关于未实现的类型类约束的类型错误,最终的原因是单态性限制,默认情况下启用.

您可以通过添加类型签名来解决此问题mysum:

mysum :: (Foldable f, Num a) => f a -> a
Run Code Online (Sandbox Code Playgroud)

或者通过关闭单态限制:

{-# LANGUAGE NoMonomorphismRestriction #-}
Run Code Online (Sandbox Code Playgroud)