简体   繁体   English

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

[英]Why does Haskell point free version of function result in ambiguous type error?

It turns out that in GHC 7.10, this compiles fine: 事实证明,在GHC 7.10中,这编译很好:

mysum xs = foldr (+) 0 xs

But this: 但是这个:

mysum    = foldr (+) 0

results in the following error: 导致以下错误:

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

Why does this happen, and what is the insight that's achieved by understanding this difference? 为什么会发生这种情况,通过了解这种差异可以获得什么? Also, can I give this function a type (that's still generic) to make this error go away? 另外,我可以给这个函数一个类型(仍然是通用的)来使这个错误消失吗?

As usual with cases where making a well-typed function point-free suddenly results in type errors about unfulfilled typeclass constraints, the ultimate cause of this is the monomorphism restriction , enabled by default. 像往常一样,如果使得一个良好类型的函数无点突然导致关于未实现的类型类约束的类型错误,则最终的原因是默认启用的单态限制

You can solve this by either adding a type signature to mysum : 您可以通过向mysum添加类型签名来解决此mysum

mysum :: (Foldable f, Num a) => f a -> a

or by turning off the monomorphism restriction: 或者通过关闭单态限制:

{-# LANGUAGE NoMonomorphismRestriction #-}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM