Haskell:将列表拆分为两个新列表的元组 [英] Haskell: Splitting list into tuple of two new lists
问题描述
我很难弄清楚如何将一个Ints列表拆分为一个包含两个新列表的元组,以便每个元素(从第一个开始)进入第一个列表,而每个其他元素进入第二个列表.
I am having difficulty figuring out how to split a list of Ints into a tuple containing two new lists, such that every element (starting with first) goes into the first list and every other element in the second.
像这样:
split [] = ([],[])
split [1] = ([1],[])
split [1,2] = ([1],[2])
split [1,2,3] = ([1,3],[2])
split [1,2,3,4] = ([1,3],[2,4])
我试图递归地(使用警卫)并仅使用单个参数xs来完成此操作
I'm trying to accomplish this recursively(with guards) and only using the single argument xs
这是我不断收到错误消息的方法:
This is my approach that keeps getting error messages:
split :: [Int] -> ([Int],[Int])
split xs | length(xs) == 0 = ([],[])
| length(xs) == 1 = (xs !! 0 : [],[])
| length(xs) == 2 = (xs !! 0 : [], xs !! 1 : [])
| otherwise = (fst ++ xs !! 0, snd ++ xs !! 1) ++ split(drop 2 xs))
推荐答案
您的split
函数返回一对,但在最后一种情况下,您对split
的结果使用++
.这将是类型错误,因为++
在列表上起作用,而不是成对出现.还有一个类型错误,因为fst
和snd
是挑选一对元素的函数,但是使用它们是一种奇怪的方式.
Your split
function returns a pair, but in the last case you are using ++
on the result of split
. That will be a type error, since ++
works on lists, not pairs. There is also a type error because fst
and snd
are functions to pick out the elements of a pair, but you are using them is a strange way.
此外,使用模式匹配而不是长度.另外,不需要测试长度是否为2的情况,因为一般情况下会删除2个元素,从而使您降至空列表的基本情况.
Furthermore, use pattern matching instead of using length. Also, the case where you test if the length is 2 is not needed, since the general case removes 2 elements which takes you down to the base case of the empty list.
还可以通过使用类型变量a
代替类型中的Int
来使函数更通用.
You can also make your function more general by using a type variable a
instead of Int
in the type.
:添加了代码
split :: [a] -> ([a], [a])
split [] = ([], [])
split [x] = ([x], [])
split (x:y:xys) = (x:xs, y:ys) where (xs, ys) = split xys
这篇关于Haskell:将列表拆分为两个新列表的元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!