5条回答
  •  盖世英雄少女心
    2020-12-19 04:32

    All you're really doing is grouping--creating a new group each time a value is encountered.

    let splitBy f input =
      let i = ref 0
      input 
      |> Seq.map  (fun x -> 
        if f x then incr i
        !i, x)
      |> Seq.groupBy fst
      |> Seq.map (fun (_, b) -> Seq.map snd b)
    

    Example

    let items = seq [1;2;3;4;1;5;6;7;1;9]
    items |> splitBy ((=) 1)
    

    Again, shorter, with Stephen's nice improvements:

    let splitBy f input =
      let i = ref 0
      input
      |> Seq.groupBy (fun x ->
        if f x then incr i
        !i)
      |> Seq.map snd
    

提交回复
热议问题