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

前端 未结 8 2084
悲&欢浪女
悲&欢浪女 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:51

    It looks like this is what you were going for, which is indeed a nice way to do it as it's tail-recursive.

    let splitList items =
      let rec splitOdd odds evens = function
        | [] -> odds, evens
        | h::t -> splitEven (h::odds) evens t
      and splitEven odds evens = function
        | [] -> odds, evens
        | h::t -> splitOdd odds (h::evens) t
      let odds, evens = splitOdd [] [] items
      List.rev odds, List.rev evens
    

提交回复
热议问题