我需要对列表中的每一项调用一个函数;如果函数返回-1,则立即退出。我需要返回函数结果的总和以及一串“Done”或“Error”。
let input = seq { 0..4 } // fake input
let calc1 x = // mimic failing after input 3. It's a very expensive function and should stop running after failing
if x >= 3 then -1 else x * 2
let run input calc =
input
|> Seq.map(fun x ->
let v = calc x
if v = -1 then .... // Error occurred, stop the execution if gets -1. Calc will not work anymore
v)
|> Seq.sum, if hasError then "Error" else "Done"
run input calc // should return (6, "Error")
run input id // should return (20, "Done")
最佳答案
有效以惯用方式准确实现要求的最简单方法是使用内部递归函数遍历序列:
let run input calc =
let rec inner unprocessed sum =
match unprocessed with
| [] -> (sum, "Done")
| x::xs -> let res = calc x
if res < 0 then (sum, "Error") else inner xs (sum + res)
inner (input |> Seq.toList) 0
然后 run (seq {0..4}) (fun x -> if x >=3 then -1 else x * 2)
返回 (6,"Error")
同时
run (seq [0;1;2;1;0;0;1;1;2;2]) (fun x -> if x >=3 then -1 else x * 2)
返回 (20, "Done")
关于f# - 打破迭代并获得值和状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52434425/