printfn "Please provide an empty interse-6ren">
gpt4 book ai didi

f# - 如何在 F# 模式匹配中 "compress"相似分支

转载 作者:行者123 更新时间:2023-12-04 22:19:21 25 4
gpt4 key购买 nike

我手头有以下代码:

    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 或其状态不同于空,我应该执行完全相同的打印一些文本并返回的分支。但是我不知道如何在 F# 中执行这种条件表达式,以便我可以共享相同的分支。在命令式编程中,我很容易做到这一点,但在 F# 中我该怎么做?

谢谢

最佳答案

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

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

否则,您可以使用 guard :
match intersection with
| Some x when x.Status = Empty ->
// Code for empty...
| _ ->
printfn "Please provide an empty intersection for ring placement"
gameState

关于f# - 如何在 F# 模式匹配中 "compress"相似分支,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39836825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com