我不能使用高阶函数。我只是无法弄清楚如何做到这一点。我对haskell很陌生。它也必须是递归的。
split :: [Int] -> ([Int],[Int])
split xs =
我被赋予了这个开始。老实说,我什至不知道从哪里开始解决这个问题。
例子:
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 :: [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:将偶数和奇数元素拆分为元组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3707753/