【发布时间】:2011-11-16 16:20:52
【问题描述】:
我很难弄清楚如何将一个 Ints 列表拆分为一个包含两个新列表的元组,这样每个元素(从第一个开始)都进入第一个列表,而其他所有元素都进入第二个列表。
像这样:
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 来完成此操作
这是我不断收到错误消息的方法:
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))
【问题讨论】:
-
你应该接受其中一个答案。