Scala有守卫吗?

时间:2010-02-15 15:23:57

标签: scala functional-programming

我几天前开始学习scala,在学习它时,我将其与其他functional programming语言(如HaskellErlang)进行比较,我对此非常熟悉。 Scala是否有guard个序列?

我在Scala中进行了模式匹配,但有没有相当于otherwise所有守卫的概念?

4 个答案:

答案 0 :(得分:54)

是的,它使用关键字if。来自斯卡拉A Tour的Case Classes部分,靠近底部:

def isIdentityFun(term: Term): Boolean = term match {
  case Fun(x, Var(y)) if x == y => true
  case _ => false
}

Pattern Matching页面上未提及此问题,可能是因为巡回赛是如此快速的概述。)


在Haskell中,otherwise实际上只是一个绑定到True的变量。因此,它不会为模式匹配的概念增添任何力量。你可以通过在没有警卫的情况下重复你的初始模式来获得它:

// if this is your guarded match
  case Fun(x, Var(y)) if x == y => true
// and this is your 'otherwise' match
  case Fun(x, Var(y)) if true => false
// you could just write this:
  case Fun(x, Var(y)) => false

答案 1 :(得分:19)

是的,有防护装置。它们的使用方式如下:

def boundedInt(min:Int, max: Int): Int => Int = {
  case n if n>max => max
  case n if n<min => min
  case n => n
}

请注意,您只需指定没有后卫的模式,而不是otherwise - 子句。

答案 2 :(得分:9)

简单的答案是否定的。它并不完全符合您的要求(与Haskell语法完全匹配)。您可以将Scala的“匹配”声明与守卫一起使用,并提供外卡,例如:

num match {
    case 0 => "Zero"
    case n if n > -1 =>"Positive number"
    case _ => "Negative number"
}

答案 3 :(得分:4)

我偶然发现了这篇文章,看看如何将警卫应用于多个参数的匹配,这不是很直观,所以我在这里添加一个随机的例子。

def func(x: Int, y: Int): String = (x, y) match {
  case (_, 0) | (0, _)  => "Zero"
  case (x, _) if x > -1 => "Positive number"
  case (_, y) if y <  0 => "Negative number"
  case (_, _) => "Could not classify"
}

println(func(10,-1))
println(func(-10,1))
println(func(-10,0))
相关问题