【问题标题】:Haskell count length using foldr throw type errorHaskell使用foldr throw类型错误计算长度
【发布时间】:2019-02-21 11:09:03
【问题描述】:

尝试通过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 拨打了电话?
  • 我只是用 GHCi 8.4.3 加载一行模块 ~\Desktop\hskl> ghci .\lenListFoldr.hs GHCi,版本 8.4.3:haskell.org/ghc :?寻求帮助 [1 of 1] 编译 Main(lenListFoldr.hs,解释) lenListFoldr.hs:1:14: 错误:* 模糊类型变量 t0' arising from a use of foldr' ....
  • length:: (Foldable f, Num a) => f a -> a 你需要明确的是 Foldable
  • @WillemVanOnsem 由于禁用了单态限制,它可以直接在 GHCi 中工作。
  • @duplode: aarrghh...是的:s.

标签: haskell types compiler-errors parametric-polymorphism monomorphism-restriction


【解决方案1】:

添加类型签名:

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。

【讨论】:

    【解决方案2】:

    可以通过类型定义来解决:

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

    很奇怪,但是如果只是将函数粘贴到解释器,没有类型定义就可以正常工作

    【讨论】:

    • “很奇怪,但是如果只是将函数粘贴到解释器,没有类型定义就可以正常工作” -- 这是因为 GHCi 默认禁用the monomorphism restriction。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    相关资源
    最近更新 更多