Slice/Group a sequence of equal chars in F#

前端 未结 6 1803
难免孤独
难免孤独 2020-12-21 15:34

I need to extract the sequence of equal chars in a text.

For example: The string \"aaaBbbcccccccDaBBBzcc11211\" should be converted to a list of strings

6条回答
  •  死守一世寂寞
    2020-12-21 15:40

    When you're folding, you'll need to carry along both the previous value and the accumulator holding the temporary results. The previous value is wrapped as option to account for the first iteration. Afterwards, the final result is extracted and reversed.

    "aaaBbbcccccccDaBBBzcc11211"
    |> Seq.map string
    |> Seq.fold (fun state ca ->
        Some ca,
        match state with
        | Some cb, x::xs when ca = cb -> x + ca::xs
        | _, xss ->                      ca::xss )
        (None, [])
    |> snd 
    |> List.rev
    // val it : string list =
    //   ["aaa"; "B"; "bb"; "ccccccc"; "D"; "a"; "BBB"; "z"; "cc"; "11"; "2"; "11"]
    

提交回复
热议问题