Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "compress" similar branches in F# pattern matching

Tags:

f#

I have the following piece of code in hand:

    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 may see, if the variable intersection is either None or its Status is different than empty, I should do exactly the same branch of printing some text and return. However I don't know how to do that kind of condition expression in F# so that I can share the same branch. In imperative programming I would do this easily, but in F# how can I do it?

Thank you

like image 514
David Jiménez Martínez Avatar asked Dec 14 '22 03:12

David Jiménez Martínez


1 Answers

If Status is a record field then 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 a guard:

match intersection with
| Some x when x.Status = Empty ->
    // Code for empty...
| _ ->
    printfn "Please provide an empty intersection for ring placement"
    gameState
like image 183
Tarmil Avatar answered Jan 12 '23 15:01

Tarmil