在F#中切片/分组一系列相等的字符

Hen*_*iro 2 f# functional-programming

我需要在文本中提取相等字符的序列.

例如:字符串"aaaBbbcccccccDaBBBzcc11211"应转换为字符串列表 ["aaa";"B";"bb";"ccccccc";"D";"a";"BBB";"z";"cc";"11";"2";"11"].

这是我的解决方案,直到现在:

let groupSequences (text:string) = 

    let toString chars =
        System.String(chars |> Array.ofList)

    let rec groupSequencesRecursive acc chars = seq {
        match (acc, chars) with
        | [], c :: rest -> 
            yield! groupSequencesRecursive [c] rest
        | _, c :: rest when acc.[0] <> c -> 
            yield (toString acc)
            yield! groupSequencesRecursive [c] rest
        | _, c :: rest when acc.[0] = c -> 
            yield! groupSequencesRecursive (c :: acc) rest
        | _, [] -> 
            yield (toString acc)
        | _ -> 
            yield ""
    }

    text
    |> List.ofSeq
    |> groupSequencesRecursive []

groupSequences "aaaBbbcccccccDaBBBzcc11211"
|> Seq.iter (fun x -> printfn "%s" x)
|> ignore
Run Code Online (Sandbox Code Playgroud)

我是F#新手.

这个解决方案可以更好吗?

Mar*_*ann 10

这是一个完全通用的实现:

let group xs =
    let folder x = function
        | [] -> [[x]]
        | (h::t)::ta when h = x -> (x::h::t)::ta
        | acc -> [x]::acc
    Seq.foldBack folder xs []
Run Code Online (Sandbox Code Playgroud)

此函数具有类型seq<'a> -> 'a list list when 'a : equality,因此不仅适用于字符串,而且适用于任何(有限)元素序列,只要元素类型支持相等比较即可.

使用在OP输入字符串,返回值是不是相当的预期形状:

> group "aaaBbbcccccccDaBBBzcc11211";;
val it : char list list =
  [['a'; 'a'; 'a']; ['B']; ['b'; 'b']; ['c'; 'c'; 'c'; 'c'; 'c'; 'c'; 'c'];
   ['D']; ['a']; ['B'; 'B'; 'B']; ['z']; ['c'; 'c']; ['1'; '1']; ['2'];
   ['1'; '1']]
Run Code Online (Sandbox Code Playgroud)

而不是a string list,返回值是a char list list.您可以使用以下命令轻松将其转换为字符串列表map:

> group "aaaBbbcccccccDaBBBzcc11211" |> List.map (List.toArray >> System.String);;
val it : System.String list =
  ["aaa"; "B"; "bb"; "ccccccc"; "D"; "a"; "BBB"; "z"; "cc"; "11"; "2"; "11"]
Run Code Online (Sandbox Code Playgroud)

这利用了String带有char[]输入的构造函数重载.

如最初所述,此实现是通用的,因此也可以与其他类型的列表一起使用; 例如整数:

> group [1;1;2;2;2;3;4;4;3;3;3;0];;
val it : int list list = [[1; 1]; [2; 2; 2]; [3]; [4; 4]; [3; 3; 3]; [0]]
Run Code Online (Sandbox Code Playgroud)