斯卡拉有警卫吗? [英] Does Scala have guards?

查看:133
本文介绍了斯卡拉有警卫吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几天前开始学习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

这篇关于斯卡拉有警卫吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆