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

标签 f#

我需要对列表中的每一项调用一个函数;如果函数返回-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/

相关文章:

c# - 是否有与 .NET Core 的 IControllerActivator 等效的 .NET Framework?

f# - 泛型函数的类型推断解决方法

f# - 有没有办法识别 F# 中的 CLR 事件实例?

c# - 素数生成器的 F# 与 C# 性能对比

f# - FSLab模板项目运行时出错

list - 如何递归地添加 F# 列表中的所有元素?

f# - 为什么 F# 不支持嵌套类?

f# - 增强了可区分联合的调试信息

f# - 使用不可变的字典

function - 这个 '()' 表示法是什么意思?