我在 Haskell 中对 Zip 的定义有什么问题?
-- eg. myzip [’a’, ’b’, ’c’] [1, 2, 3, 4] -> [(’a’, 1), (’b’, 2), (’c’, 3)]
myzip :: Ord a => [a] -> [a] -> [(a,a)]
myzip list1 list2 = [(x,y) | [x, _] <-list1, [y,_] <-list2 ]
我收到此错误消息:
Occurs check: cannot construct the infinite type: a = [a]
When generalising the type(s) for `myzip'
Failed, modules loaded: none.
-- eg. myzip [’a’, ’b’, ’c’] [1, 2, 3, 4] -> [(’a’, 1), (’b’, 2), (’c’, 3)]
myzip :: Ord a => [a] -> [a] -> [(a,a)]
myzip list1 list2 = [(x,y) | [x, _] <-list1, [y,_] <-list2 ]
I get this error message:
Occurs check: cannot construct the infinite type: a = [a]
When generalising the type(s) for `myzip'
Failed, modules loaded: none.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
存在三个问题:一是模式匹配,一是类型签名,一是列表理解的性质。这是更正后的版本:
[a] -> [一]-> [(a, a)]
,意味着两个列表必须具有相同类型的元素。Ord a
是多余的,仅意味着某些类型的元素是不允许的。[x, _] <- list1
表示list1
的每个元素必须是一个二元素列表。使用 x <- list1 来代替。串联和并联的区别:
There are three problems: One is the pattern match, one is the type signature, and one is the nature of the list comprehension. Here is a corrected version:
[a] -> [a] -> [(a, a)]
, meant that both lists had to have the same type of element. TheOrd a
was superfluous, and just meant that certain types of elements were disallowed.[x, _] <- list1
means that each element oflist1
must be a two-element list. Usex <- list1
instead.The difference between series and parallel:
如果您重写
zip
以便深入了解 Haskell,我建议您尝试在不使用列表理解的情况下编写它。列表推导式很强大,但有点像 Haskell 中某些特定情况的方便简写。而且,如您所见,在其他情况下使用它们可能需要非标准扩展(例如ParallelListComp
)。考虑一下
zip
在一般情况下需要做什么,以及如果不满足一般情况会发生什么(这可能以两种方式发生!)。该函数的方程应该自然地从其中得出。If you re-writing
zip
in order to gain insight into Haskell, I'd suggest that you try to write it without using list comprehensions. List comprehensions are powerful, but are somewhat like a convenient shorthand for some particular cases in Haskell. And, as you see, to use them in other cases might require non-standard extensions (such asParallelListComp
).Think about what
zip
needs to do in the general case, and what happens if the general case isn't met (which can happen in two ways!). The equations for the function should fall naturally out of that.