Is it possible to implement a recursive “SelectMany”?

前端 未结 2 1390
天命终不由人
天命终不由人 2020-12-18 23:24

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

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-19 00:09

    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"]
    

提交回复
热议问题