gpt4 book ai didi

Haskell:将偶数和奇数元素拆分为元组

转载 作者:行者123 更新时间:2023-12-03 06:31:05 24 4
gpt4 key购买 nike

我无法使用高阶函数。我只是不知道如何做到这一点。我对 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com