打破迭代并获得值和状态?

ca9*_*3d9 2 f#

我需要对列表中的每个项目调用一个函数;如果函数返回-1,则立即退出。我需要返回函数结果的总和以及“完成”或“错误”字符串。

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")
Run Code Online (Sandbox Code Playgroud)

Gen*_*ski 5

有效地准确实现惯用方式所要求的最简单方法是使用内部递归函数来遍历序列:

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 Code Online (Sandbox Code Playgroud)

然后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")