Merge two lists

后端 未结 6 1877
暖寄归人
暖寄归人 2020-12-10 14:01

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])

6条回答
  •  借酒劲吻你
    2020-12-10 14:35

    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.

    • We match on the first branch because the left list is not empty.
    • We yield the head of the first list (1).
    • We then recurse into the function with the second list and the tail of the first list. Note that the order of the parameters was swapped.

    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.

    • The list is not empty so we match on the first branch.
    • We yield the head of the list (4).
    • We then recurse again, switching the parameters once more.

    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.

提交回复
热议问题