E.Y
E.Y

Reputation: 23

Converting a list of integers to a tuple of lists

I'm trying to convert a list of integers to a tuple of lists in a recursive function.

Let's say I have a list of integers as [1;2;3;4;5;6;7;8] and I want to turn this into ([1;3;5;7],[2;4;6;8]) dividing odds and evens on different sides

I'm facing with a lot of problems such as expected result being 'a list * 'a list and I'm having a 'b * 'c even tho 'b & 'c are lists of integers.

Upvotes: 1

Views: 219

Answers (1)

ildjarn
ildjarn

Reputation: 63015

Since you asked specifically for a recursive function..:

let partitionNumbers nums =
    let rec impl odds evens = function
      | []                   -> odds, evens
      | n::ns when n % 2 = 1 -> impl (n::odds) evens ns
      | n::ns                -> impl odds (n::evens) ns
    List.rev nums |> impl [] []

However the more idiomatic approach is (as almost-always) to use higher-order functions:

let partitionNumbers = List.partition (fun n -> n % 2 = 1)

Upvotes: 6

Related Questions