F# 忽略模式匹配中的模式

Luk*_*keP 1 f# functional-programming pattern-matching

我可能会以错误的方式思考这个问题,但我想忽略除Some案例之外的任何案例。这是我正在使用的一些示例代码,| _ -> ignore但这似乎是错误的。有没有更好或更惯用的方法来做到这一点?我正在将一些 OOP C# 代码转换为 F#,可能会出错。

match solarSystem.MinerCoords |> Map.tryFind minerId with
| Some currentMinerCoords ->
    match solarSystem.Minables |> Map.tryFind currentMinerCoords with
    | Some _ ->
        do! GetMinerActor(minerId).StopMining() |> Async.AwaitTask
    | _ -> ignore
| _ -> ignore
Run Code Online (Sandbox Code Playgroud)

The*_*Fox 5

看起来您在一个async返回的计算表达式中Async<unit>。所以你应该替换ignorereturn ()(where ()is the unit value) 以便所有分支返回相同的类型:

match solarSystem.MinerCoords |> Map.tryFind minerId with
| Some currentMinerCoords ->
    match solarSystem.Minables |> Map.tryFind currentMinerCoords with
    | Some _ ->
        do! GetMinerActor(minerId).StopMining() |> Async.AwaitTask
    | _ -> return ()
| _ -> return ()
Run Code Online (Sandbox Code Playgroud)

编辑:显示整个异步块的简化版本,以及之后如何继续运行更多代码:

async {
    match Some 1 with
    | Some a ->
        printfn "Maybe do this"
        do! Async.Sleep 500
    | _ -> ()

    printfn "Always do this"
    do! Async.Sleep 500
    printfn "Finished" }
Run Code Online (Sandbox Code Playgroud)