将项目列表拆分为奇数和偶数索引项目的两个列表 [英] Splitting a list of items into two lists of odd and even indexed items
本文介绍了将项目列表拆分为奇数和偶数索引项目的两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想做一个接受列表并返回两个列表的函数:第一个包含每个奇数项,第二个包含每个偶数项.
I would like to make a function that accepts a list and returns two lists: the first contains every odd item, and the second contains every even item.
例如,给定 [1;2;4;6;7;9]
,我想返回 [ [1;4;7] ;[2;6;9] ]
.
For example, given [1;2;4;6;7;9]
, I would like to return [ [1;4;7] ; [2;6;9] ]
.
我写到这里为止,我不知道如何进行.
I have written this so far and I do not know how to progress.
let splitList list =
let rec splitOdd oList list1 list2 =
match oList with
| [] -> []
| head :: tail -> splitEven tail (list1::head) list2
and splitEven oList list1 list2 =
match oList with
| [] -> []
| head :: tail -> splitOdd tail list1 (list2::head)
splitOdd list [] []
推荐答案
不发生堆栈溢出的实现:
Implementation which does not stack-overflows:
let splitList list = List.foldBack (fun x (l,r) -> x::r, l) list ([],[])
这篇关于将项目列表拆分为奇数和偶数索引项目的两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文