我几天前开始学习scala,在学习它的时候,我正在将它与其他的进行比较functional programming像( Haskell , Erlang )这样的语言我有一些熟悉。 Scala 有 guard序列可用吗?
我在 Scala 中进行了模式匹配,但是有没有与 otherwise
和所有的守卫等效的概念?
最佳答案
是的,它使用关键字if
。来自 Case Classes Scala 之旅的部分,靠近底部:
def isIdentityFun(term: Term): Boolean = term match {
case Fun(x, Var(y)) if x == y => true
case _ => false
}
(Pattern Matching 页面上没有提到这一点,可能是因为游览是如此快速的概述。)
<小时/>在 Haskell 中,otherwise
实际上只是一个绑定(bind)到 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
关于scala - Scala 有守卫吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2266915/