如何在 Scala 中对某个范围进行模式匹配?
在 Ruby 中我可以这样写:
case n
when 0...5 then "less than five"
when 5...10 then "less than ten"
else "a lot"
end
How do I do this in Scala?
编辑:最好我想比使用 if
做得更优雅。
In Ruby I can write this:
case n
when 0...5 then "less than five"
when 5...10 then "less than ten"
else "a lot"
end
How do I do this in Scala?
Edit: preferably I'd like to do it more elegantly than using if
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
内部模式匹配可以用守卫来表示:
Inside pattern match it can be expressed with guards:
与@Yardena的答案类似,但使用基本比较:
也适用于浮点n
Similar to @Yardena's answer, but using basic comparisons:
Also works for floating point n
请注意,Contains 实例的命名应使用首字母大写。如果不这样做,则需要在反引号中给出名称(这里很困难,除非有我不知道的转义)
Note that Contains instances should be named with initial caps. If you don't, you'll need to give the name in back-quotes (difficult here, unless there's an escape I don't know)
对于相同大小的范围,您可以用老式数学来完成:
是的,我知道:“没有必要不要除!”
但是:分而治之!
For Ranges of equal size, you can do it with old-school math:
Yes, I know: "Don't divide without neccessity!"
But: Divide et impera!