haskell - 使用 ListLike 的二义性类型

标签 haskell types type-inference strong-typing

我正在用 Haskell 编写一个函数来从任何 ListLike 制作直方图与 Ord元素:

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 作为元素”这样的类型,即 full0 ?

最佳答案

Is Haskell somehow unable to infer that there is such a type as "ListLike with full as elements", i.e full0?



不,问题是要选择的类型太多full0 from 并且 Haskell 编译器不知道使用哪个。想一想:一般来说,可以有不止一种类型full0这是一个类似列表的类型,带有 full作为元素:[full]Data.Sequence.Seq full或许多其他选择。并且因为LL.map定义的一般性, full0不限于 [full]来自函数的返回类型 frequencies .

如果您想限制full0[full] ,一种方法是替换 LL.mapfrequencies的定义中与普通的旧 map对于列表。

关于haskell - 使用 ListLike 的二义性类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6404989/

相关文章:

haskell - 如何让Haskell程序响应用户输入显示初步结果?

haskell - 没有 arr 的箭头

arrays - Julia 中的通用数值数组

python - 正确使用 Python 泛型 - 如何获取泛型 var 的类型并在初始化后在对象内强制执行一致的类型?

c# - C# 中的类型推断

带有菱形运算符的 Java 对象初始化糟糕的 javac 编译时间性能

Kotlin 对 "supposedly"正确类型的类型推断

Haskell 十进制转二进制

Haskell - 如何在实例中简单地生成 "div"或 "/"?

c++ - 为什么我不能将 && 添加到 Ret (Args...) &?