是否已经有一种方法可以执行 achooseTill
或 a之类的操作foldTill
,在收到 None 选项之前它会一直处理?实际上,任何带有“直到”选项的高阶函数。诚然,像地图这样的东西没有意义,但我发现我经常需要这种东西,我想确保我没有重新发明轮子。
一般来说,写这样的东西很容易,但我很好奇是否已经有办法做到这一点,或者这是否存在于某个已知的库中?
let chooseTill predicate (sequence:seq<'a>) =
seq {
let finished = ref false
for elem in sequence do
if not !finished then
match predicate elem with
| Some(x) -> yield x
| None -> finished := true
}
let foldTill predicate seed list =
let rec foldTill' acc = function
| [] -> acc
| (h::t) -> match predicate acc h with
| Some(x) -> foldTill' x t
| None -> acc
foldTill' seed list
let (++) a b = a.ToString() + b.ToString()
let abcdef = foldTill (fun acc v ->
if Char.IsWhiteSpace v then None
else Some(acc ++ v)) "" ("abcdef ghi" |> Seq.toList)
// result is "abcdef"