我有一个返回的函数(我们称之为“doSomething”):
('a * 'b) option
Run Code Online (Sandbox Code Playgroud)
并希望实现这样的目标:
let testA = doSomething ....
if testA.IsSome then return testA.Value
let testB = doSomething ....
if testB.IsSome then return testB.Value
let testC = doSomething ....
if testC.IsSome then return testC.Value
Run Code Online (Sandbox Code Playgroud)
我正在寻找一个计算表达式或等效的简单语法,它会在结果为 None 时继续执行,但保留第一个 Some 结果。
显然我想避免while if / elif / elif / ... / elif / else 厄运金字塔。
一种选择(呵呵)是将Option模块中的一些调用链接在一起,如下所示:
let doSomething doThisOne tup = if doThisOne then Some tup else None
let f () =
doSomething false (1, 2)
|> Option.orElseWith (fun () -> doSomething false (2, 3))
|> Option.orElseWith (fun () -> doSomething true (3, 4))
|> Option.defaultValue (0, 0)
f () // Evaluates to (3, 4)
Run Code Online (Sandbox Code Playgroud)
您也许可以对optionCE使用 FsToolkit.ErrorHandling 和应用语法,但我不知道组合结果的好方法会是什么样子,所以我个人只会像上面那样链接调用。
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |