Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Interleave 2 lists [duplicate]

Tags:

list

f#

Is there a way that I could merge 2 lists

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

so I get this result

result = ["a"; "d"; "b"; "b"; "c"; "a"]
like image 867
Mark Avatar asked Dec 02 '22 14:12

Mark


2 Answers

This task is best solved by 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"]
like image 153
David Raab Avatar answered Dec 14 '22 22:12

David Raab


A quick & dirty solution would be to zip the two list, then flatten the resulting tuples:

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

This returns a list with the interleaved 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 collect will flatten the tuples

like image 24
Panagiotis Kanavos Avatar answered Dec 14 '22 23:12

Panagiotis Kanavos