I am looking to merge 2 lists in F# in a purely functional way. I am having a hard time understanding the syntax.
Let say I have a tuple ([5;3;8],[2;9;4])
Gonna throw another variation into the mix. This handles lists of different lengths by simply appending the remainder of the longer list at the end.
let rec interleave lst1 lst2 = [
match lst1 with
| lst1H :: lst1T ->
yield lst1H
yield! interleave lst2 lst1T
| [] -> yield! lst2
]
How it works:
Assuming we have let a = [1;2;3]; let b = [4;5;6] and call interleave a b.
1).At this intermediate point we've two lists: the remainder of the first one [2;3] and the second one [4;5;6]. Since we swapped the order of the arguments, we're now focusing on the second list.
4).The lists at this point are [2;3] and [5;6] while the output contains [1;4].
This process repeats until the operated list is empty, which matches into the second branch, yielding the remainder of the other list.