Haskell:将偶数和奇数元素拆分为元组 [英] Haskell: split even and odd elements into tuple
本文介绍了Haskell:将偶数和奇数元素拆分为元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不能使用高阶函数.我只是看不出如何做到这一点.我对Haskell非常陌生.它也必须是递归的.
I can't use high order functions. I just can't see to figure out how to do this. I am very new to haskell. It also has to be recursive.
split :: [Int] -> ([Int],[Int])
split xs =
我首先得到这个.老实说,我什至不知道从哪里开始这个问题.
I am given this to start with. I honestly don't even know where to start with this problem.
示例:
split []
([],[])
split [1]
([1],[])
split [1,2,3,4,5,6,7,8,9,10]
([1,3,5,7,9],[2,4,6,8,10])
任何帮助将不胜感激.
其偶数和奇数位置.
所以
分割[3,6,8,9,10]将是 ([3,8,10],[6,9])
split [3,6,8,9,10] would be ([3,8,10],[6,9])
好的,所以我想到了这个.它不漂亮,但是看起来还可以.
ok so i came up with this. Its not pretty, but it seems to work ok.
split :: [Int] -> ([Int],[Int])
split [] = ([],[])
split [xs] = ([xs],[])
split xs = (oddlist xs, evenlist xs)
oddlist :: [Int] -> ([Int])
oddlist xs | length xs <= 2 = [head(xs)]
| otherwise = [head(xs)] ++ oddlist(tail(tail(xs)))
evenlist :: [Int] -> ([Int])
evenlist xs | length xs <= 3 = [head(tail(xs))]
| otherwise = [head(tail(xs))] ++ evenlist(tail(tail(xs)))
推荐答案
split [] = ([], [])
split [x] = ([x], [])
split (x:y:xs) = (x:xp, y:yp) where (xp, yp) = split xs
这篇关于Haskell:将偶数和奇数元素拆分为元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文