[英]Haskell, reverse two elements in list?
i want to take a list and always reverse two elements. 我想列出一个清单,并总是反转两个元素。 Example:
例:
input 1: [1,2,3,4,5]
, output 1: [2,1,4,3,5]
输入1:
[1,2,3,4,5]
,输出1: [2,1,4,3,5]
input 2: [1,2,3,4,5,6]
output 2: [2,1,4,3,6,5]
输入2:
[1,2,3,4,5,6]
输出2: [2,1,4,3,6,5]
I tried it with pattern matching: 我尝试了模式匹配:
g1 [] = []
g1 (x:y:xs) = y: x: g1 xs
But it says: 但它说:
*Main> g1 [1,2,3]
*** Exception: test.hs:(13,1)-(14,27): Non-exhaustive patterns in function g1
g1
Has anybody an idea to solve this problem? 有没有人想解决这个问题?
The problem is that when you apply this, for instance on the list [1,2,3,4,5]
. 问题是,当您应用此功能时,例如在列表
[1,2,3,4,5]
。 It runs as follows: 它运行如下:
g1 [1,2,3,4,5]
= 1 : 2 : g1 [3,4,5]
= 4 : 3 : g1 [5]
and there is no pattern defined for the list contain one single element (here [5]
). 并且没有为包含一个元素的列表定义模式(此处为
[5]
)。 Based on your first example nothing should be done in such case except emitting the element. 根据您的第一个示例,在这种情况下,除了发出元素之外,什么也不要做。 So you have to add the case:
因此,您必须添加案例:
g1 [x] = [x]
Or the entire function definition: 或整个函数定义:
g1 [] = []g1 [x] = [x] g1 (x:y:xs) = y: x: g1 xs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.