我正在使用来自猫库的State-Monad来处理我在Scala中实现的纸牌游戏的状态。
我有一个函数simulateGame
,它应该在当前状态为Over
时立即结束。该功能看起来像这样。
def simulateGame: GameState[Outcome] = for {
action <- State.inspect[PlayerState, Action] { ... }
status <- step(action)
outcome <- ???
} yield outcome
step
函数返回当前步骤之后的状态。根据返回的状态,我想要从状态中提取结果(这是没有问题的,因为如果状态是Over
则编码结果)或者对simulateGame
函数进行递归调用。
我不知道如何模式匹配状态,然后进行递归调用。
任何帮助表示赞赏!
你可以匹配并递归
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