【问题标题】:logic and if inside match case in scalascala中的逻辑和if内部匹配案例
【发布时间】:2017-03-05 07:31:31
【问题描述】:

我需要在scala中使用一堆match case,如果在match case里面怎么用for或者if,例如:

import scala.util.Random

val x = Random.nextInt(30)
val result = match x {
case 0 to 10 => bad
case 11 to 20 => average
case 20 to 30 => cool
}

第一个问题是我该怎么做而不是使用floorceilround 或其他数学东西?

其次,对于字符串值,在 php 中我们可以轻松使用if (x == 'some')||(x == 'thing'){result},但这在 scala 匹配情况下如何工作?

例如当 val x 是随机的 A 到 I 时:

val result = match x {
case A || B || C => bad
case D || E || F => average
case G || H || I => cool
}

谢谢!

【问题讨论】:

  • 但不一样@YuvalItzchakov 我的问题还包括字符串,我认为Pamu 的回答比使用if state 好得多
  • 那里的答案不使用if-else 表达式。此外,通过查看如何将守卫与整数一起使用,您可以推断出如何对字符串执行相同的操作。

标签: string scala logic match case


【解决方案1】:

这是一个更接近您的伪代码的替代方案:

val x:Int  

val result = x match {
  case x if (1 to 10).contains(x) => "bad"
  case x if (11 to 20).contains(x) => "average"
  case x if (21 to 30).contains(x) => "cool"
  case _ => "unknown"
}


val y:String 

val result = y match  {
    case "A" | "B" | "C" => "bad"
    case "D" | "E" | "F" => "average"
    case "G" | "H" | "I" => "cool"
    case _ => "unknown"
}

为了利用第一个示例中的范围,将字母分数视为字符会更方便:

val z:Char 

val result = z match {
  case x if ('A' to 'C').contains(x) => "bad"
  case x if ('D' to 'F').contains(x) => "average"
  case x if ('G' to 'I').contains(x) => "cool"
  case _ => "unknown"
}

【讨论】:

    【解决方案2】:

    使用 Guards 的模式匹配可以帮助您做到这一点

    val x = Random.nextInt(30)
    
    val result = x match {
     case x if x > 0 && x <= 10 => "bad"
     case x if x > 11 &&  x <= 20 => "average"
     case x if x > 20 && x <= 30 => "cool"
     case _ => "no idea"
    }
    

    对于字符串,您可以这样做

    val str = "foo"
    
    val result = str match {
     case "foo" => "found foo"
     case "bar" => "found bar"
     case _ => "found some thing"
    }
    

    你也可以使用|

    val result = str match {
      case "foo" | "bar" => "match"
      case _ => "no match"
    }
    

    Scala REPL

    scala> :paste
    // Entering paste mode (ctrl-D to finish)
    
    val x = Random.nextInt(30)
    
    val result = x match {
     case x if x > 0 && x <= 10 => "bad"
     case x if x > 11 &&  x <= 20 => "average"
     case x if x > 20 && x <= 30 => "cool"
     case _ => "no idea"
    }
    
    // Exiting paste mode, now interpreting.
    
    x: Int = 13
    result: String = average
    

    【讨论】:

    • 我可以这样做吗? "foo" && "bar" =>
    • @DedenBangkit 一个字符串不能同时是foobar
    猜你喜欢
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多