在Scala的功能步骤之间传递状态

时间:2019-06-11 18:12:29

标签: scala functional-programming scala-cats

是否有更好的方法在步骤之间传递状态。

例如,每次从卡组中取出一张卡片时,我们都必须创建一个新的Deck并将其返回,以便下一步可以使用它,等等。

例如,使用Cats是否有更好的方法?

trait BlackjackSteps {
    def gamerTakesTwoCards(deck: Deck): (Gamer, Deck)
    def dealerTakesTwoCards(deck: Deck): (Dealer, Deck)
    def isBlackjack(gamer: Gamer, dealer: Dealer): Option[Player]
    def gamerToDrawCards(gamer: Gamer, deck: Deck): Gamer
    def dealerToDrawCards(dealer: Dealer, deck: Deck, gamer: Gamer): Dealer
    def determineWinner(gamer: Gamer, dealer: Dealer): Player
  }

游戏:

  • 玩家和发牌人
  • 他们俩都抓了两张牌
  • 如果没有21名获胜者
  • 玩家保留抽奖牌直到17
  • 最高得分不超过21分的玩家

编辑-----

感谢您的答复。我只想看看人们对这种方法的看法?

怎么样?

trait CardPicker {
    def pick(numberCards:Int): List[Card]
  }

  abstract class BlackjackSteps(cardPicker: CardPicker) {
    def gamerTakesTwoCards(gamer: Gamer): Gamer = {
      gamer.copy(cards = cardPicker.pick(2))
    }
    def dealerTakesTwoCards(dealer: Dealer): Dealer = {
      dealer.copy(cards = cardPicker.pick(2))
    }
    def isBlackjack(gamer: Gamer, dealer: Dealer): Option[Player] = {
     if(gamer.isBlackjack) Some(gamer)
     else if(dealer.isBlackjack) Some(dealer)
     else None
    }
    def gamerToDrawCards(gamer: Gamer): Gamer = {
      def drawCards(gamerPickingCards: Gamer): Gamer = gamer match {
        case _ if(gamerPickingCards.points < drawThreshold) =>
          drawCards(Gamer(gamerPickingCards.name, gamerPickingCards.cards ++ cardPicker.pick(1)))
        case _ => gamerPickingCards
      }
      drawCards(gamer)
    }
    def dealerToDrawCards(dealer: Dealer, gamer: Gamer): Dealer = {
      def drawCards(dealerPickingCards: Dealer): Dealer = dealer match {
        case _ if(dealerPickingCards.points < gamer.points) =>
          drawCards(Dealer(dealerPickingCards.name, dealerPickingCards.cards ++ cardPicker.pick(1)))
        case _ => dealerPickingCards
      }
      drawCards(dealer)
    }
    def determineWinner(gamer: Gamer, dealer: Dealer): Player = {
      if(gamer.points == dealer.points || gamer.points > dealer.points) gamer
      else dealer
    }
  }

在此CardPicker具有副作用,我们可以将其推迟到世界末日。

这太疯狂了吗?

1 个答案:

答案 0 :(得分:5)

这听起来像State单子的一个很好的用例。这可以帮助您入门:

trait BlackjackSteps {
  def gamerTakesTwoCards: State[Deck, Gamer]
  def dealerTakesTwoCards: State[Deck, Dealer]
  def isBlackjack(gamer: Gamer, dealer: Dealer): State[Deck, Option[Player]]
  def gamerToDrawCards(gamer: Gamer): State[Deck, Gamer]
  def dealerToDrawCards(dealer: Dealer, gamer: Gamer): State[Deck, Dealer]
  def determineWinner(gamer: Gamer, dealer: Dealer): State[Deck, Player]
}

def gamerTakesTwoCards: State[Deck, Gamer] = 
  State { oldDeck => 
    val gamer = f(oldDeck)
    val newDeck = g(oldDeck)
    (newDeck, gamer)
  } 

您可以查看Cats的官方文档以了解更多信息: https://typelevel.org/cats/datatypes/state.html