[英]Haskell count length using foldr throw type error
尝试通过foldr函数实现列表计数
lengthList = foldr (\x s -> s + 1) 0
给出以下错误
* 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
我该如何解决这个问题?
添加类型签名:
lengthList :: [a] -> Int
或类似的东西。 错误说明:“可能的修复:使用类型注释来指定`t0'应该是什么。” 换句话说,编译器无法推断出类型。 或者,作为注释声明:在上下文中使用该函数,然后编译器将使用上下文来推断lengthList
正确类型。 我相信函数foldr
使用类约束Foldable t
; 在您的情况下,编译器不知道lengthList
正在折叠。 通过给出上面的签名,你将t0
绑定为一个列表。 看看GHCi给出的输出
:t foldr
foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b
简而言之,GHC可以发现a
未使用且b
是Num
,但它不知道t
。
它可以通过类型定义来解决:
lengthList :: (Foldable t, Num a1) => t a2 -> a1
这很奇怪,但如果只是将函数粘贴到解释器,它将在没有类型定义的情况下正常工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.