我几天前开始学习scala,在学习它时,我将它与其他函数式编程类似的语言( Haskell , Erlang ),我对它有一定的了解。 Scala是否有守卫序列?
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中进行了模式匹配,但是有没有相当于使用的守卫的概念,否则和所有?
I went through pattern matching in Scala, but is there any concept equivalent to guards with otherwise and all?
推荐答案是的,如果使用关键字。来自斯卡拉A Tour之旅的案例分类部分,靠近底部:
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中,否则实际上只是一个绑定到 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更多推荐
斯卡拉有警卫吗?
发布评论