Splitting a list of items into two lists of odd and even indexed items

前端 未结 8 2075
悲&欢浪女
悲&欢浪女 2020-12-11 00:56

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.

For example, g

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-11 01:34

    Sounds like you want List.partition<'T> ( http://msdn.microsoft.com/en-us/library/ee353782.aspx ). This function takes a predicate and a list and will return a pair (2-tuple) where the first element is all the elements that passed your test and the second is all the elements that did not pass the test. So you could classify odds and evens with:

    List.partition odd [1;2;4;6;7;9]
    

    If your really want a list, you can use fst and snd to extract the elements from the tuple and put them in a list.

    Good luck!

提交回复
热议问题