How to "compress" similar branches in comparison with the F # sample
I have the following code:
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
As you can see, if the intersection of the variables is either None, or its status is different from empty, I have to do exactly the same branch of printing some text and return. However, I do not know how to make such a condition expression in F # so that I can split a single branch. In imperative programming, I would do it easily, but in F #, how can I do this?
thank
If Statusis a record field, you can do:
match intersection with
| Some { Status = Empty } ->
// Code for empty...
| _ ->
printfn "Please provide an empty intersection for ring placement"
gameState
Otherwise, you can use protection:
match intersection with
| Some x when x.Status = Empty ->
// Code for empty...
| _ ->
printfn "Please provide an empty intersection for ring placement"
gameState