Scala 有守卫吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2266915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does Scala have guards?
提问by Teja Kantamneni
I started learning scala a few days ago and when learning it, I am comparing it with other functional programminglanguages like (Haskell, Erlang) which I had some familiarity with. Does Scala has guardsequences available?
几天前我开始学习 scala,在学习它时,我将它与我熟悉的其他函数式编程语言(如Haskell、Erlang)进行了比较。Scala 有可用的保护序列吗?
I went through pattern matching in Scala, but is there any concept equivalent to guards with otherwiseand all?
我在 Scala 中进行了模式匹配,但是否有任何与守卫otherwise和所有等价的概念?
回答by Nathan Shively-Sanders
Yes, it uses the keyword if. From the Case Classessection of A Tour of Scala, near the bottom:
是的,它使用关键字if。来自A Tour of Scala的案例类部分,靠近底部:
def isIdentityFun(term: Term): Boolean = term match {
case Fun(x, Var(y)) if x == y => true
case _ => false
}
(This isn't mentioned on the Pattern Matchingpage, maybe because the Tour is such a quick overview.)
(这在Pattern Matching页面上没有提到,可能是因为 Tour 是一个快速概述。)
In Haskell, otherwiseis actually just a variable bound to True. So it doesn't add any power to the concept of pattern matching. You can get it just by repeating your initial pattern without the guard:
在 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
回答by sepp2k
Yes, there are pattern guards. They're used like this:
是的,有模式守卫。它们是这样使用的:
def boundedInt(min:Int, max: Int): Int => Int = {
case n if n>max => max
case n if n<min => min
case n => n
}
Note that instead of an otherwise-clause, you simply specifiy the pattern without a guard.
请注意,不是 -otherwise子句,您只需指定没有保护的模式。
回答by Shaun
The simple answer is no. It is not exactly what you are looking for (an exact match for Haskell syntax). You would use Scala's "match" statement with a guard, and supply a wild card, like:
简单回答是不。它不是您正在寻找的(与 Haskell 语法完全匹配)。您可以将 Scala 的“match”语句与守卫一起使用,并提供一个通配符,例如:
num match {
case 0 => "Zero"
case n if n > -1 =>"Positive number"
case _ => "Negative number"
}
回答by cevaris
I stumbled to this post looking how to apply guards to matches with multiple arguments, it is not really intuitive, so I am adding an random example here.
我偶然发现了这篇关于如何将守卫应用于具有多个参数的匹配项的帖子,这不是很直观,所以我在这里添加了一个随机示例。
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))

