使用 ListLike 的不明确类型
我正在 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
< code>LL.group 的类型为 (ListLike full0 full, ListLike full item, Eq item) =>满-> full0
对应于 (Eq a) => [a]->[[a]]
用普通列表来说。
我不明白为什么类型不明确会出现问题。 Haskell 是否无法推断出存在这样一种类型:“ListLike with full
as elements”,即 full0
?
I'm writing a function in Haskell to make a histogram from any ListLike
with Ord
elements:
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
When trying to compile the above code i get an error message about ambiguous types:
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
has type (ListLike full0 full, ListLike full item, Eq item) => full -> full0
which corresponds to (Eq a) => [a]->[[a]]
speaking in terms of ordinary lists.
I dont understand why there is a problem with ambigious types. Is Haskell somehow unable to infer that there is such a type as "ListLike with full
as elements", i.e full0
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,问题是有太多类型可供选择
full0
,而 Haskell 编译器不知道该使用哪个。想一想:一般来说,可以有多个类型full0
,它是一种类似列表的类型,以full
作为元素:[full]
或Data.Sequence.Seq full
或许多其他选择。并且由于LL.map
定义的通用性,full0
不被限制为[full]
来自函数频率的返回类型。如果要将
full0
限制为[full]
,一种方法是替换定义中的
与普通的旧LL.map
频率map
列表。No, the problem is there are too many types to choose
full0
from and the Haskell compiler does not know which to use. Think about it: in general, there can be more than one typefull0
which is a list-like type withfull
as elements:[full]
orData.Sequence.Seq full
or many other choices. And because of the generality of the definition ofLL.map
,full0
is not constrained to be[full]
from the return type of the functionfrequencies
.If you want to restrict
full0
to[full]
, one way to do this is to replaceLL.map
in the definition offrequencies
with the plain oldmap
for lists.