【发布时间】:2017-09-18 01:34:30
【问题描述】:
我正在尝试编写一个函数,该函数将三个列表作为参数,并从每个列表中连续创建一个包含三元组的列表。
给我的例子是这样的:zip3Lists [1, 2, 3] [4, 5, 6] ['a', 'b', 'c'] 会产生[(1, 4, 'a'), (2, 5, 'b'), (3, 6, 'c')]。
到目前为止,我所拥有的是:
zipThree [] [] [] = []
zipThree [] [] [x] = [x]
zipThree [] [x] [] = [x]
zipThree [x] [] [] = [x]
zipThree (x:xs) (y:ys) (z:zs) = (x, y, z) : zipThree xs ys zs
它给了我这个错误:
haskell1.hs:32:33: error:
• Occurs check: cannot construct the infinite type: c ~ (c, c, c)
Expected type: [c]
Actual type: [(c, c, c)]
• In the expression: (x, y, z) : zipThree xs ys zs
In an equation for ‘zipThree’:
zipThree (x : xs) (y : ys) (z : zs) = (x, y, z) : zipThree xs ys zs
• Relevant bindings include
zs :: [c] (bound at haskell1.hs:32:27)
z :: c (bound at haskell1.hs:32:25)
ys :: [c] (bound at haskell1.hs:32:20)
y :: c (bound at haskell1.hs:32:18)
xs :: [c] (bound at haskell1.hs:32:13)
x :: c (bound at haskell1.hs:32:11)
(Some bindings suppressed; use -fmax-relevant-binds=N or -fno-max-relevant-binds)
【问题讨论】:
-
您期望
zipThree [1, 2, 3] [4, 5, 6] [‘a’, ‘b’, ‘c’, 'd']的结果是什么?长度为 3 或 4 的列表?你的实现是做什么的?有意义吗? -
我们假设每个列表的长度相同,因此不处理您提到的情况
-
@Vic 但是您有不同长度列表的明确案例,因此您正在处理它。问题是:您是否按照预期的方式处理它? (听起来不,如果你不打算处理它!)
-
我的印象是这是一个与作业相关的问题,这很好,但是对于以后来这个问题的其他人来说,这个功能是内置的,称为
zip3。一般情况下,当您想要组合 n 列表时,可以使用ZipList应用函子来解决。