我正在用 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.efull0
?
不,问题是要选择的类型太多
full0
from 并且 Haskell 编译器不知道使用哪个。想一想:一般来说,可以有不止一种类型full0
这是一个类似列表的类型,带有 full
作为元素:[full]
或 Data.Sequence.Seq full
或许多其他选择。并且因为LL.map
定义的一般性, full0
不限于 [full]
来自函数的返回类型 frequencies
.如果您想限制
full0
至 [full]
,一种方法是替换 LL.map
在frequencies
的定义中与普通的旧 map
对于列表。
关于haskell - 使用 ListLike 的二义性类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6404989/