gpt4 book ai didi

Scala:使用模式匹配检测 5 张扑克牌中的顺牌

转载 作者:行者123 更新时间:2023-12-02 07:46:00 24 4
gpt4 key购买 nike

对于那些不知道 5 张扑克顺子是什么的人:http://en.wikipedia.org/wiki/List_of_poker_hands#Straight

我正在用 Scala 编写一个小型扑克模拟器来帮助我学习这门语言,并且我创建了一个Hand 类,其中包含 5 张有序的 Cards。每张 Card 都有一个 RankSuit,两者都定义为 EnumerationsHand 类具有评估手牌排名的方法,其中之一检查手牌是否包含顺子(我们暂时可以忽略同花顺)。我知道有一些不错的算法可以确定 Straight,但我想看看我是否可以用 Scala 的模式匹配设计一些东西,所以我想出了以下方法:

def isStraight() = {
def matchesStraight(ranks: List[Rank.Value]): Boolean = ranks match {
case head :: Nil => true
case head :: tail if (Rank(head.id + 1) == tail.head) => matchesStraight(tail)
case _ => false
}

matchesStraight(cards.map(_.rank).toList)
}

它工作正常并且相当可读,但我想知道是否有任何方法可以摆脱 if。我想像下面这样的东西,虽然我不能让它工作:

private def isStraight() = {
def matchesStraight(ranks: List[Rank.Value]): Boolean = ranks match {
case head :: Nil => true
case head :: next(head.id + 1) :: tail => matchesStraight(next :: tail)
case _ => false
}

matchesStraight(cards.map(_.rank).toList)
}

有什么想法吗?另外,作为附带问题,对内部 matchesStraight 定义的普遍看法是什么?这应该是私有(private)的还是以不同的方式完成?

最佳答案

您不能将信息传递给提取器,也不能使用从一个值返回到另一个值的信息,if 语句除外——它涵盖了所有这些情况。

你可以做的是创建你自己的提取器来测试这些东西,但如果没有任何重用,它不会给你带来太多好处。

例如:

class SeqExtractor[A, B](f: A => B) {
def unapplySeq(s: Seq[A]): Option[Seq[A]] =
if (s map f sliding 2 forall { case Seq(a, b) => a == b } ) Some(s)
else None
}

val Straight = new SeqExtractor((_: Card).rank)

然后你可以像这样使用它:

listOfCards match {
case Straight(cards) => true
case _ => false
}

但是,当然,您真正想要的只是 SeqExtractor 中的 if 语句。所以,不要太迷恋解决方案,因为您可能会错过更简单的做事方式。

关于Scala:使用模式匹配检测 5 张扑克牌中的顺牌,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6985148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com