F # - splitting a list into tuples of odd-even lists (by element, not position)

Example: split [1;3;2;4;7;9];;


Output:([1;3;7;9], [2;4])

I'm new to F # and I can't seem to figure it out.
Cannot use built-in function partition

.

This is what I have so far:

let rec split xs = 
    match xs with
    | [] -> [], []
    | xs -> xs, []
    | xh::xt -> let odds, evens = split xt
                if (xh % 2) = 0 then xh::odds, xh::evens
                else xh::odds, evens  

      

Fixed code:

let rec split xs = 
    match xs with
    | [] -> [], []
    | xh::xt -> let odds, evens = split xt
                if (xh % 2) = 0 then odds, xh::evens
                else xh::odds, evens

      

* Thanks to @TheInnerLight for pointing out my mistakes: unreachable case and unnecessary change in odds

+3


source to share


1 answer


You can use the built-in function List.partition

let splitOddEven xs =
    xs |> List.partition (fun x -> x % 2 <> 0)

      

splitOddEven [1;3;2;4;7;9];;
val it : int list * int list = ([1; 3; 7; 9], [2; 4])

      



If you want a recursive implementation, I would probably go for a recursive tail implementation like this:

let splitOddEven xs =
    let rec splitOddEvenRec oddAcc evenAcc xs = 
        match xs with
        | [] -> oddAcc, evenAcc
        | xh::xt -> 
            if (xh % 2) = 0 then splitOddEvenRec oddAcc (xh :: evenAcc) xt
            else splitOddEvenRec (xh :: oddAcc) evenAcc xt
    splitOddEvenRec [] [] xs

splitOddEven  [1;3;2;4;7;9]

      

Note that this will give you two resulting lists in reverse order so you can undo them yourself.

+8


source







All Articles