Scala 有守卫吗? [英] Does Scala have guards?
问题描述
几天前我开始学习scala,在学习它时,我将它与其他函数式编程进行了比较 语言,如 (Haskell、Erlang),我对它有些熟悉.Scala 是否有可用的guard 序列?
I started learning scala a few days ago and when learning it, I am comparing it with other functional programming languages like (Haskell, Erlang) which I had some familiarity with. Does Scala has guard sequences available?
我在 Scala 中经历了模式匹配,但是否有任何概念等同于 otherwise
和 all 的守卫?
I went through pattern matching in Scala, but is there any concept equivalent to guards with otherwise
and all?
推荐答案
是的,它使用关键字 if
.来自 Scala 之旅的案例类部分,靠近底部:
Yes, it uses the keyword if
. From the Case Classes section of A Tour of Scala, near the bottom:
def isIdentityFun(term: Term): Boolean = term match {
case Fun(x, Var(y)) if x == y => true
case _ => false
}
(模式匹配页面上没有提到这一点,可能是因为 Tour是一个如此快速的概述.)
(This isn't mentioned on the Pattern Matching page, maybe because the Tour is such a quick overview.)
在 Haskell 中,otherwise
实际上只是一个绑定到 True
的变量.所以它不会为模式匹配的概念增加任何力量.你可以通过在没有守卫的情况下重复你的初始模式来获得它:
In Haskell, otherwise
is 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:
// 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
这篇关于Scala 有守卫吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!