Merge two lists

后端 未结 6 1888
暖寄归人
暖寄归人 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:56

    One important point is that the function is not correct. It fails with the input ([1;2;3], []) since you missed the case of (xs, []) in pattern matching. Moreover, arguments are better in the curried form in order that it's easier to use with partial application. Here is the corrected version:

    let rec interleave xs ys =
        match xs, ys with
        | [], ys -> ys
        | xs, [] -> xs
        | x::xs', y::ys' -> x::y::interleave xs' ys'
    

    You can see that the function is not tail-recursive since it applies cons (::) constructor twice after the recursive call returned. One interesting way to make it tail-recursive is using sequence expression:

    let interleave xs ys =
        let rec loop xs ys = 
           seq {
                 match xs, ys with
                 | [], ys -> yield! ys
                 | xs, [] -> yield! xs
                 | x::xs', y::ys' -> 
                       yield x
                       yield y
                       yield! loop xs' ys'
                }
        loop xs ys |> List.ofSeq
    

提交回复
热议问题