這裏是一個短:
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"]]
這滿足於問題的規範:I would like to start a new sequence whenever "a" is encountered
,因爲之前,首先任何初始字符串「a」將被忽略。例如,對於
let inputSequence =
["r"; "s";
"a"; "b"; "c";
"a"; "b"; "c"; "d";
"a"; "b";
"a"; "d"; "f";
"a"; "x"; "y"; "z"]
得到與上述相同的結果。
如果人們需要第一個「一」以下之前捕捉到初始字符串可以使用:
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"]]
要做到這一點,最好的辦法可能是使用'List.fold' –