代码之家  ›  专栏  ›  技术社区  ›  Theo

如何在scala的范围内进行模式匹配?

  •  38
  • Theo  · 技术社区  · 14 年前

    在Ruby中,我可以写下:

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

    我在斯卡拉怎么做?

    编辑:最好我想做的比使用更优雅 if .

    4 回复  |  直到 9 年前
        1
  •  64
  •   Yardena    14 年前

    内部模式匹配可以用防护装置表示:

    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"
    }
    
        2
  •  13
  •   Randall Schulz    14 年前
    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
    

    请注意,包含实例的名称应使用初始大写字母。如果你不这样做,你需要在后面的引号中加上这个名字(这里很难,除非我不知道有一个转义)

        3
  •  9
  •   gens    9 年前

    类似于@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

        4
  •  4
  •   user unknown    14 年前

    对于相同大小的范围,可以使用旧的学校数学:

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

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