F # Interleave 2 Lists

Is there a way I could combine 2 lists

let a = ["a"; "b"; "c"]
let b = ["d"; "b"; "a"]

so i get this result

result = ["a"; "d"; "b"; "b"; "c"; "a"]
+4
source share
3 answers

A quick and dirty solution would be to fasten the two lists and then smooth the resulting tuples:

let interleave a b =
    List.zip a b |> List.collect (fun (a,b)-> [a;b])

Returns a list with alternating elements:

interleave a b;;
val it : string list = ["a"; "d"; "b"; "b"; "c"; "a"]

zip will create pairs from the elements of both lists:

val it : (string * string) list = [("a", "d"); ("b", "b"); ("c", "a")]

and collectwill smooth tuples

+5
source

This task is best solved foldBack2:

let al = ["a"; "b"; "c"]
let bl = ["d"; "b"; "a"]

List.foldBack2 (fun a b xs -> a :: b :: xs) al bl []
// ["a"; "d"; "b"; "b"; "c"; "a"]
+8
source

@Panagiotis Kanavos, , , ( ):

let interleave a b =
    let rec loop acc a b =
        match a, b with
        | [], l | l, [] -> List.rev l @ acc
        // Or if you want to fail when the lengths are different, replace the above with:
        // | [], [] -> acc
        // | [], _ | _, [] -> failwith "interleave: List lengths are different"
        | a :: aa, b :: bb -> loop (b :: a :: acc) aa bb
    loop [] a b |> List.rev

( , )

+3
source

Source: https://habr.com/ru/post/1656096/


All Articles