I've done some research and I see that the List.zip function takes two lists and returns one list of tuples, but how do you change one list into a list of tuples?
let rec combinePair xs =
match xs with
| [] -> []
| [x1] -> []
| x1::x2::x3::xs -> [(x1, x2)]
| x1::x2::xs -> [(x1, x2)]
If an odd number of elements exist in the list, the last element should be dropped, if an even number of elements exist they should be returned as a list of tuples. For example
combinePair [x1; x2; x3; x4] = [(x1, x2); (x3, x4)]
Your code is almost there.
Here's the thinking:
This can be almost identically translated to F#:
let rec combinePair xs =
match xs with
| [] | [_] -> []
| x1::x2::rest -> (x1, x2) :: (combinePair rest)
(note how I combined the first two cases on one line, [] | [_] ->
)
I'm sure there are prettier solutions but for those who are allergic to recursion:
let xsOdd = [1;2;3;4;5]
List.chunkBySize 2 xsOdd
|> List.filter (fun x -> x.Length = 2)
|> List.map (fun x -> x.[0],x.[1])
//val it : (int * int) list = [(1, 2); (3, 4)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With