Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursions with the State-Monad

I am using the State-Monad from the cats library to take care of the state of a card game I am implementing in Scala.

I have a function simulateGame which should end as soon as the status of a the current state is Over. The function looks like this.

def simulateGame: GameState[Outcome] = for {
    action <- State.inspect[PlayerState, Action] { ... }
    status <- step(action)
    outcome <- ???
} yield outcome

The step function returns the status after the current step. Depending on the returned status I want to either extract the outcome from the status (this is no problem since the outcome is encoded if the status is Over) or do a recursive call to the simulateGame function.

I am not sure how to pattern match on the status and then do the recursive call.

Any help is appreciated!

like image 989
Lando-L Avatar asked Oct 20 '25 14:10

Lando-L


1 Answers

You can just match and recurse

def simulateGame: GameState[Outcome] = for {
    action <- State.inspect[PlayerState, Action] { ... }
    status <- step(action)
    outcome <- status match
       case o: Over => State.pure(o)
       case _ => simulateGame
} yield outcome
like image 160
emilianogc Avatar answered Oct 22 '25 04:10

emilianogc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!