As we all know, Enumerable.SelectMany
flattens a sequence of sequences into a single sequence. What if we wanted a method that could flatten sequences of sequen
This is trivial in F# with recursive sequence expressions.
let rec flatten (items: IEnumerable) =
seq {
for x in items do
match x with
| :? 'T as v -> yield v
| :? IEnumerable as e -> yield! flatten e
| _ -> failwithf "Expected IEnumerable or %A" typeof<'T>
}
A test:
// forces 'T list to obj list
let (!) (l: obj list) = l
let y = ![["1";"2"];"3";[!["4";["5"];["6"]];["7"]];"8"]
let z : string list = flatten y |> Seq.toList
// val z : string list = ["1"; "2"; "3"; "4"; "5"; "6"; "7"; "8"]