Here is a short one:
let folder (str: string) ((xs, xss): list<string> * list<list<string>>) =
if str = "a" then ([], ((str :: xs) :: xss))
else (str :: xs, xss)
List.foldBack folder inputSequence ([], [])
|> snd
// [["a"; "b"; "c"]; ["a"; "b"; "c"; "d"]; ["a"; "b"]; ["a"; "d"; "f"]; ["a"; "x"; "y"; "z"]]
This satisfies the specifications in the question: I would like to start a new sequence whenever "a" is encountered
since any leading lines before the first "a" will be ignored. For example, for
let inputSequence =
["r"; "s";
"a"; "b"; "c";
"a"; "b"; "c"; "d";
"a"; "b";
"a"; "d"; "f";
"a"; "x"; "y"; "z"]
it turns out the same result as above.
If you need to wrap the starting lines before the first "a", you can use the following:
match inputSequence |> List.tryFindIndex (fun x -> x = "a") with
| None -> [inputSequence]
| Some i -> (List.take i inputSequence) ::
(List.foldBack folder (List.skip i inputSequence) ([], []) |> snd)
// [["r"; "s"]; ["a"; "b"; "c"]; ["a"; "b"; "c"; "d"]; ["a"; "b"];
["a"; "d"; "f"]; ["a"; "x"; "y"; "z"]]
source
share