斯卡拉有警卫吗?

编程入门 行业动态 更新时间:2024-10-11 11:18:55
本文介绍了斯卡拉有警卫吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

斯卡拉有警卫吗?

本文发布于:2023-07-15 13:17:34,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:警卫   斯卡

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!