【问题标题】:Pattern matching in ScalaScala 中的模式匹配
【发布时间】:2012-10-31 07:36:57
【问题描述】:
scala> (1,5) == BigInt(12) /% 7
res3: Boolean = true

scala> BigInt(12) /% 7 match {
 | case (1,5) => true
 | }

<console>:9: error: type mismatch;
found   : Int(1)
required: scala.math.BigInt
          case (1,5) => true
                ^

有人可以解释一下如何在这里进行模式匹配吗?

【问题讨论】:

    标签: scala pattern-matching bigint


    【解决方案1】:

    15Int 类型。模式匹配需要scala.math.BigInt。因此,通过为 1 和 5 声明几个 val 来实现这一点。

    scala> val OneBig = BigInt(1)
    oneBig: scala.math.BigInt = 1
    
    scala> val FiveBig = BigInt(5)
    fiveBig: scala.math.BigInt = 5
    
    scala> BigInt(12) /% 7 match {
         | case (OneBig, FiveBig) => true
         | }
    res0: Boolean = true
    

    【讨论】:

    • 这行不通!模式中的oneBigfiveBig 是与之前定义的变量无关的新变量。这可以通过用大写字母命名它们(OneBigFiveBig)或用反引号括起来来更改。
    • 谢谢。忘了那个。对于那些感兴趣的人,请参阅stackoverflow.com/questions/4479474/… 或楼梯书的第 317 页。
    【解决方案2】:

    match 比相等更具体;你不能只是相等,你也必须有相同的类型。

    在这种情况下,BigInt 不是一个案例类,并且它的伴生对象中没有unapply 方法,所以你不能直接匹配它。你能做的最好的就是

      BigInt(12) /% 7 match {
        case (a: BigInt,b: BigInt) if (a==1 && b==5) => true
        case _ => false
      }
    

    或其一些变体(例如case ab if (ab == (1,5)) =&gt;)。

    或者,您可以使用适当类型的 unapply 方法创建一个对象:

    object IntBig { def unapply(b: BigInt) = Option(b.toInt) }
    
    scala> BigInt(12) /% 7 match { case (IntBig(1), IntBig(5)) => true; case _ => false }
    res1: Boolean = true
    

    【讨论】:

    • 绑定到变量和守卫是我所做的。我只是觉得它也许可以做得更好一点。谢谢。
    【解决方案3】:

    问题在于/% 返回的15BigInts,因此即使equals 方法(由== 调用)返回true,也不匹配文字Ints .这可行,但有点不雅:

    scala> BigInt(12) /% 7 match { case (x, y) if x == 1 && y == 5 => true }
    res3: Boolean = true
    

    【讨论】:

      猜你喜欢
      • 2016-05-17
      • 2021-12-17
      • 2016-03-29
      • 2019-05-26
      • 1970-01-01
      • 1970-01-01
      • 2014-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多