functional programming - Slice/Group a sequence of equal chars in F# -


i need extract sequence of equal chars in text.

for example: string "aaabbbcccccccdabbbzcc11211" should converted list of strings ["aaa";"b";"bb";"ccccccc";"d";"a";"bbb";"z";"cc";"11";"2";"11"].

that's solution until now:

let groupsequences (text:string) =       let tostring chars =         system.string(chars |> array.oflist)      let rec groupsequencesrecursive acc chars = seq {         match (acc, chars)         | [], 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 

i'm f# newbie.

this solution can better?

here generic implementation:

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

this function has type seq<'a> -> 'a list list when 'a : equality, works not on strings, on (finite) sequence of elements, long element type supports equality comparison.

used input string in op, return value isn't quite in expected shape:

> group "aaabbbcccccccdabbbzcc11211";; val : 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']] 

instead of string list, return value char list list. can convert list of strings using map:

> group "aaabbbcccccccdabbbzcc11211" |> list.map (list.toarray >> system.string);; val : system.string list =   ["aaa"; "b"; "bb"; "ccccccc"; "d"; "a"; "bbb"; "z"; "cc"; "11"; "2"; "11"] 

this takes advantage of string constructor overload takes char[] input.

as stated, implementation generic, can used other types of lists; e.g. integers:

> group [1;1;2;2;2;3;4;4;3;3;3;0];; val : int list list = [[1; 1]; [2; 2; 2]; [3]; [4; 4]; [3; 3; 3]; [0]] 

Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -