【问题标题】:Ambiguous types using ListLike使用 ListLike 的模糊类型
【发布时间】:2011-06-19 20:38:04
【问题描述】:

我正在 Haskell 中编写一个函数,从任何带有 Ord 元素的 ListLike 制作直方图:

import qualified Data.ListLike as LL
...
frequencies :: (Ord x, LL.ListLike xs x) => xs -> [(x, Int)]
frequencies xs = LL.map (\x->(LL.head x, LL.length x)) $ LL.group $ LL.sort xs

在尝试编译上述代码时,我收到一条关于不明确类型的错误消息:

 Ambiguous type variable `full0' in the constraint:
 (LL.ListLike full0 xs) arising from a use of `LL.group'
 Probable fix: add a type signature that fixes these type variable(s)
 In the expression: LL.group
 In the second argument of `($)', namely `LL.group $ LL.sort xs'
 In the expression:
 LL.map (\ x -> (LL.head x, LL.length x)) $ LL.group $ LL.sort xs

LL.group 的类型为(ListLike full0 full, ListLike full item, Eq item) => full -> full0,对应于普通列表中的(Eq a) => [a]->[[a]]

我不明白为什么模棱两可的类型会出现问题。 Haskell 是否无法以某种方式推断存在“ListLike with full as elements”之类的类型,即full0

【问题讨论】:

    标签: haskell types type-inference strong-typing


    【解决方案1】:

    Haskell 是否以某种方式无法推断存在“ListLike with full as elements”之类的类型,即full0

    不,问题是有太多类型可供选择 full0 并且 Haskell 编译器不知道该使用哪个。想一想:一般情况下,full0 可以有多个类型,它是一种以full 为元素的类列表类型:[full]Data.Sequence.Seq full 或许多其他选择。并且由于LL.map 定义的普遍性,full0 从函数frequencies 的返回类型限制为[full]

    如果要将full0 限制为[full],一种方法是将frequencies 定义中的LL.map 替换为用于列表的普通旧map

    【讨论】:

    • 明确地说,full0LL.group 的输出类型,然后是LL.map 的输入,然后输出另一种类型(此处为普通列表)。这与show . read 问题基本相同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    • 2019-04-22
    • 1970-01-01
    • 2014-04-09
    相关资源
    最近更新 更多