简体   繁体   English

使用foldr throw类型错误的Haskell计数长度

[英]Haskell count length using foldr throw type error

Trying to implement list counting through foldr function 尝试通过foldr函数实现列表计数

lengthList = foldr (\x s -> s + 1) 0 

gives following error 给出以下错误

   * Ambiguous type variable `t0' arising from a use of `foldr'
  prevents the constraint `(Foldable t0)' from being solved.
  Relevant bindings include
    lengthList :: t0 a -> Integer (bound at lenListFoldr.hs:2:1)
  Probable fix: use a type annotation to specify what `t0' should be.
  These potential instances exist:
    instance Foldable (Either a) -- Defined in `Data.Foldable'
    instance Foldable Maybe -- Defined in `Data.Foldable'
    instance Foldable ((,) a) -- Defined in `Data.Foldable'
    ...plus one other
    ...plus 23 instances involving out-of-scope types
    (use -fprint-potential-instances to see them all)
* In the expression: foldr (\ x s -> s + 1) 0
  In an equation for `lengthList':
      lengthList = foldr (\ x s -> s + 1) 0

How can I fix that? 我该如何解决这个问题?

Add type signature: 添加类型签名:

lengthList :: [a] -> Int

Or something similar. 或类似的东西。 The error states: "Probable fix: use a type annotation to specify what `t0' should be." 错误说明:“可能的修复:使用类型注释来指定`t0'应该是什么。” In other words, the compiler could not infer the type. 换句话说,编译器无法推断出类型。 Or, as a comment states: use the function in a context, then the compiler will use the context to infer correct type for lengthList . 或者,作为注释声明:在上下文中使用该函数,然后编译器将使用上下文来推断lengthList正确类型。 I believe the function foldr uses a class constraint Foldable t ; 我相信函数foldr使用类约束Foldable t ; in your case, the compiler doesn't know what lengthList is folding. 在您的情况下,编译器不知道lengthList正在折叠。 By giving the signature above, you bound t0 to be a list. 通过给出上面的签名,你将t0绑定为一个列表。 Take a look at the output GHCi gives for 看看GHCi给出的输出

:t foldr
foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b

In short, GHC can figure out that a is unused and b is a Num , but it does not know t . 简而言之,GHC可以发现a未使用且bNum ,但它不知道t

It can be solved by type definition: 它可以通过类型定义来解决:

lengthList :: (Foldable t, Num a1) => t a2 -> a1

It strange, but if just paste function to interpreter, it will be works fine without type definition 这很奇怪,但如果只是将函数粘贴到解释器,它将在没有类型定义的情况下正常工作

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

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