如何"压缩" F#模式匹配中的类似分支

时间:2016-10-03 17:07:40

标签: f#

我手头有以下代码:

    match intersection with
    | None ->
        printfn "Please provide an empty intersection for ring placement"
        gameState
    | Some x ->
        match x.Status with
        | Empty ->
            let piece = { Color = gameState.Active.Color; Type = Ring }
            putPieceOnIntersection gameState.Board pos piece

            printfn "%s ring placed at %A" (colorStr gameState.Active.Color) pos

            // Decide if we ended this phase
            let updatedPhase = if ringsPlaced = 10 then Main else Start(ringsPlaced + 1)
            let newActivePlayer = gameState.Players |> Array.find (fun p -> p.Color = invertColor gameState.Active.Color)
            let updatedGameState = { gameState with Active = newActivePlayer; CurrentPhase = updatedPhase }

            updatedGameState
        | _ ->
            printfn "Please provide an empty intersection for ring placement"
            gameState

正如您所看到的,如果变量交集是None或其Status不同于empty,我应该完全相同的分支打印一些文本并返回。但是,我不知道如何在F#中执行这种条件表达式,以便我可以共享同一个分支。在命令式编程中,我会很容易地做到这一点,但在F#中我该怎么做?

谢谢

1 个答案:

答案 0 :(得分:12)

如果Status是记录字段,那么您可以执行以下操作:

match intersection with
| Some { Status = Empty } ->
    // Code for empty...
| _ ->
    printfn "Please provide an empty intersection for ring placement"
    gameState

否则,您可以使用警卫:

match intersection with
| Some x when x.Status = Empty ->
    // Code for empty...
| _ ->
    printfn "Please provide an empty intersection for ring placement"
    gameState