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

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

    Here is a straightforward non-recursive solution:

    let splitList ll =
        ll
        |> List.mapi (fun i x -> (i % 2 = 0, x))
        |> List.partition fst
        |> fun (odd,even) -> [List.map snd odd, List.map snd even];;
    
    val splitList : 'a list -> 'a list list
    

    Being applied to your sample it yields exactly what you wanted:

    splitList [1;2;4;6;7;9];;
    
    val it : int list list = [[1; 4; 7]; [2; 6; 9]]
    
    0 讨论(0)
  • 2020-12-11 01:53

    My 2¢, in OCaml, since there still is a bounty open.

    Maybe you could give us a hint what you want. Elegance? FP? Tail recursion? Performance?

    Edit:

    I removed the longer solution. For List.partition to work, the predicate was missing. Here it is:

    let so_split lst = 
      let flag = ref false in
      List.partition (fun e -> flag := not !flag; !flag) lst
    

    Improvements any? Testing the solution:

    # so_split [1;2;4;6;7;9];;
    - : int list * int list = ([1; 4; 7], [2; 6; 9])
    
    0 讨论(0)
提交回复
热议问题