Haskell,一个列表中的两个元素后跟一个元素其他列表? (模式匹配)

时间:2016-05-03 21:30:32

标签: list haskell pattern-matching

我有一个函数,它将从一个列表中获取两个元素,从第二个列表中获取一个元素,但如果给定列表只有一个元素,则会出现问题:

示例:

*Main> g2 [1] [5..10]
[1]

我希望得到这样的输出:

*Main> g2 [1] [5..10]
[1,5]

适用于包含多个元素的列表:

*Main> g2 [1..5] [8..10]
[1,2,8,3,4,9,5]
*Main> g2 [1,2,3,4] [6,7,8,9]
[1,2,6,3,4,7]

我的代码:

g2 (x1:x2:xs) (y:ys) = x1:x2:y:(g2 xs ys)
g2 (x1:[]) y = x1:[]
g2 [] ys = []

我想我忘了一个模式。

1 个答案:

答案 0 :(得分:2)

您的问题令人困惑,这就是答案:

g2 (x1:x2:xs) (y:ys) = x1:x2:y:(g2 xs ys)
g2 (x1:[]) (y:ys) = x1:y:[]
g2 [] [] = []
-- Added missing patterns, don't know what the function is supposed to do here
g2 [] (y:ys) = []
g2 (x1:xs) [] = []