Tej*_*eni 45 functional-programming scala
我几天前开始学习scala,在学习它时,我将它与其他函数式编程语言(如Haskell,Erlang)进行比较,我对它很熟悉.Scala是否有可用的保护序列?
我在Scala中进行了模式匹配,但是有没有相当于守卫的概念otherwise?
Nat*_*ers 54
是的,它使用关键字if.从A Tour of Scala 的Case Classes部分,靠近底部:
def isIdentityFun(term: Term): Boolean = term match {
case Fun(x, Var(y)) if x == y => true
case _ => false
}
Run Code Online (Sandbox Code Playgroud)
(这在模式匹配页面上没有提到,可能是因为Tour是如此快速的概述.)
在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
Run Code Online (Sandbox Code Playgroud)
sep*_*p2k 19
是的,有模式保护.它们的使用方式如下:
def boundedInt(min:Int, max: Int): Int => Int = {
case n if n>max => max
case n if n<min => min
case n => n
}
Run Code Online (Sandbox Code Playgroud)
请注意otherwise,您只需指定没有防护的模式,而不是-clause.
简单回答是不.它并不完全符合您的要求(与Haskell语法完全匹配).你可以使用Scala的"匹配"声明与一名后卫,并提供一张外卡,如:
num match {
case 0 => "Zero"
case n if n > -1 =>"Positive number"
case _ => "Negative number"
}
Run Code Online (Sandbox Code Playgroud)