【问题标题】:How can I pattern match on a range in Scala?如何在 Scala 中的范围内进行模式匹配?
【发布时间】:2011-03-10 19:22:17
【问题描述】:

在 Ruby 中我可以这样写:

case n
when 0...5  then "less than five"
when 5...10 then "less than ten"
else "a lot"
end

如何在 Scala 中做到这一点?

编辑:最好比使用if 更优雅。

【问题讨论】:

标签: scala pattern-matching range


【解决方案1】:
class Contains(r: Range) { def unapply(i: Int): Boolean = r contains i }

val C1 = new Contains(3 to 10)
val C2 = new Contains(20 to 30)

scala> 5 match { case C1() => println("C1"); case C2() => println("C2"); case _ => println("none") }
C1

scala> 23 match { case C1() => println("C1"); case C2() => println("C2"); case _ => println("none") }
C2

scala> 45 match { case C1() => println("C1"); case C2() => println("C2"); case _ => println("none") }
none

请注意,Contains 实例应以首字母大写命名。如果不这样做,则需要在反引号中给出名称(在这里很难,除非有我不知道的转义)

【讨论】:

    【解决方案2】:

    在模式匹配内部可以用守卫表示:

    n match {
      case it if 0 until 5 contains it  => "less than five"
      case it if 5 until 10 contains it => "less than ten"
      case _ => "a lot"
    }
    

    【讨论】:

    • 这是 Scala 模式匹配对普通的旧 if-else 链完全没有好处的情况之一。此外,使用 Range 并没有比旧的 0 <= n && n < 5 术语提供任何好处。
    • 我认为这在计算上也更加昂贵。当您的意思是 a 时,生成一个序列来设置成员资格
    【解决方案3】:

    对于大小相等的范围,您可以使用老式数学来做到这一点:

    val a = 11 
    (a/10) match {                      
        case 0 => println (a + " in 0-9")  
        case 1 => println (a + " in 10-19") } 
    
    11 in 10-19
    

    是的,我知道:“没有必要,不要分裂!” 但是:分而治之!

    【讨论】:

      【解决方案4】:

      类似于@Yardena 的回答,但使用基本比较:

      n match {
          case i if (i >= 0 && i < 5) => "less than five"
          case i if (i >= 5 && i < 10) => "less than ten"
          case _ => "a lot"
      }
      

      也适用于浮点数n

      【讨论】:

      • 我更喜欢这种写条件的方式。 ? 一个细节:括号是不必要的; case i if i &gt;= 0 &amp;&amp; i &lt; 5 足够了(使用你喜欢的任何东西)。
      猜你喜欢
      • 2018-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      • 2011-10-02
      • 2021-04-08
      • 1970-01-01
      • 2015-04-02
      相关资源
      最近更新 更多