function - 为什么 Haskell 无点函数版本会导致模棱两可的类型错误?

标签 function haskell types monomorphism-restriction

事实证明,在 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

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

最佳答案

像往常一样,使类型良好的函数无点突然导致关于未满足的类型类约束的类型错误,最终原因是 monomorphism restriction , 默认启用。

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

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

或者通过关闭单态限制:
{-# LANGUAGE NoMonomorphismRestriction #-}

关于function - 为什么 Haskell 无点函数版本会导致模棱两可的类型错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30181658/

相关文章:

php - mysql 中的 num_row 操作?

haskell - Typeable 类型的“模式匹配”

types - 获得路径归纳以在 Agda 中工作

C 中类型之间的转换

ios - 如何在应用程序启动时调用在特定 View Controller 中找到的函数?

function - 如何在Rust中将通用函数指针存储为 `any`?

haskell - 强制性和存在主义

c++ - 使用 "|"中断 Cpp 循环

arrays - 数组公式在 Excel 中不起作用

haskell - 为什么这个 Yampa 弹球会陷入死循环?