Merge two lists

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

    From the OP it's not clear what should happen if the lists have different lengths, but here's a generic, tail-recursive implementation that fully consumes both lists:

    // 'a list -> 'a list -> 'a list
    let interleave xs ys =
        let rec imp xs ys acc =
            match xs, ys with
            |    [],    [] -> acc
            | x::xs,    [] -> imp xs [] (x::acc)
            |    [], y::ys -> imp [] ys (y::acc)
            | x::xs, y::ys -> imp xs ys (y::x::acc)
        imp xs ys [] |> List.rev
    

    Examples:

    > interleave [5;3;8] [2;9;4];;
    val it : int list = [5; 2; 3; 9; 8; 4]
    > interleave [] [1..3];;
    val it : int list = [1; 2; 3]
    > interleave [1..3] [42];;
    val it : int list = [1; 42; 2; 3]
    > interleave [1..3] [42;1337];;
    val it : int list = [1; 42; 2; 1337; 3]
    > interleave [42; 1337] [1..3];;
    val it : int list = [42; 1; 1337; 2; 3]
    

提交回复
热议问题