Scala:解析模式匹配的不明确类型

Scala:解析模式匹配的不明确类型,scala,pattern-matching,Scala,Pattern Matching,我问了一个问题,得到了很好的回答。在评论中,Travis提到比较两个HandValues不会直接起作用,但是可以使用模式匹配来确保比较相同的类 sealed abstract class HandValue[T <: HandValue[T]](val rank: Int) extends Ordered[T] case class HighCard(high: Int) extends HandValue[HighCard](0){ def compare(that: H

我问了一个问题,得到了很好的回答。在评论中,Travis提到比较两个
HandValue
s不会直接起作用,但是可以使用模式匹配来确保比较相同的类

  sealed abstract class HandValue[T <: HandValue[T]](val rank: Int) extends Ordered[T]
  case class HighCard(high: Int) extends HandValue[HighCard](0){
    def compare(that: HighCard) = this.high - that.high
  }

  case class TwoPair(high: Int, big: Int, sm: Int) extends HandValue[TwoPair](2) {
    def compare (that: TwoPair) = { ... }
  }
编辑:编译时错误为:

error: type arguments [_$3] do not conform to class HandValue's type parameter bounds [T <: euler.solutions.p54.HandValue[T]]
(h1, h2) match {

错误:类型参数[$3]不符合类HandValue的类型参数界限[T对错误没有帮助,但是您可以通过允许将任何
HandValue
与任何其他
HandValue
进行比较来消除很多这种复杂性;这样您就不必进行可怕的参数化和重复的
compare
方法,然后在
ans
中重复比较逻辑

一种方法是让每个人定义一个
强度
,这是一个
Seq[Int]
,由手牌等级和手牌中定义其强度的牌的等级组成。然后你只需通过找出哪个数字更大来比较这些
Seq

sealed abstract class HandValue(val strength: Seq[Int]) extends Ordered[HandValue] {
  import math.Ordering.Implicits.seqDerivedOrdering
  def compare(that: HandValue) = 
    Ordering[Seq[Int]].compare(this.strength, that.strength)
}

case class HighCard(high1: Int, high2: Int, high3: Int, high4: Int, high5: Int ) 
  extends HandValue(Seq(0, high1, high2, high3, high4, high5))

case class TwoPair(high: Int, big: Int, sm: Int) 
  extends HandValue(Seq(2, big, sm, high))

val ans = sessions count { hands => 
  handValue(hands._1) > handValue(hands._2)
}
注意,在计算高牌手强度时,你需要考虑所有的牌。还要注意a-to-5直杆


您也可以使用散列函数将
strength
计算为
Int

编译时错误是什么?啊,对不起,很好!我忘了粘贴它。顺便问一下,Hand和HandValue之间的关系是什么?
键入Hand=Array[Card]
其中
具有
c.suit
c.value
,然后使用数组的属性计算
HandValue
——例如,如果对于
Hand h
h.forall(u.suit==h(0).suit)
,然后它有
HandValue
Flush
的子类。你在写机器人吗?)我最后做了一些与你建议的类似的事情——谢谢!
sealed abstract class HandValue(val strength: Seq[Int]) extends Ordered[HandValue] {
  import math.Ordering.Implicits.seqDerivedOrdering
  def compare(that: HandValue) = 
    Ordering[Seq[Int]].compare(this.strength, that.strength)
}

case class HighCard(high1: Int, high2: Int, high3: Int, high4: Int, high5: Int ) 
  extends HandValue(Seq(0, high1, high2, high3, high4, high5))

case class TwoPair(high: Int, big: Int, sm: Int) 
  extends HandValue(Seq(2, big, sm, high))

val ans = sessions count { hands => 
  handValue(hands._1) > handValue(hands._2)
}