我几天前开始学习scala,在学习它时,我将其与其他functional programming语言(如Haskell,Erlang)进行比较,我对此有一些熟悉。斯卡拉是否有guard序列可用?斯卡拉是否有警卫?
我经历了Scala中的模式匹配,但是有没有相当于otherwise
和所有的守卫的概念?
我几天前开始学习scala,在学习它时,我将其与其他functional programming语言(如Haskell,Erlang)进行比较,我对此有一些熟悉。斯卡拉是否有guard序列可用?斯卡拉是否有警卫?
我经历了Scala中的模式匹配,但是有没有相当于otherwise
和所有的守卫的概念?
是的,它使用关键字if
。从斯卡拉之旅的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
是的,有花纹守卫。他们使用的是这样的:
def boundedInt(min:Int, max: Int): Int => Int = {
case n if n>max => max
case n if n<min => min
case n => n
}
注意,而不是otherwise
-clause,只需specifiy格局没有保护。
简单的答案是否定的。这不正是你正在寻找的(与Haskell语法完全匹配)。你可以使用Scala的“匹配”的声明与保护,并提供一张外卡,如:
num match {
case 0 => "Zero"
case n if n > -1 =>"Positive number"
case _ => "Negative number"
}
我无意中发现这个帖子寻找如何卫士适用于具有多个参数匹配,它是不是真的直观,所以我在这里添加一个随机的例子。
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))
在这种情况下,'n'是什么,请给出一个工作示例。 – Jet
@Jet'n'将作为该函数的参数。 [Here](http://ideone.com/HhSuF0)是使用该函数的一个例子。 – sepp2k
明白了,谢谢:-) – Jet