如何|(管道)在模式匹配工作? [英] How does | (pipe) in pattern matching work?

查看:25
本文介绍了如何|(管道)在模式匹配工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你可以写:

str match { case "foo" | "bar" => ... }

乍一看,| 可能是一个提取器对象,但是:

At first glance it looks like | could be an extractor object, however:

str match { case |("foo", "bar") => ... }

不起作用.(无论如何我都看不出这是如何实现的.)

does not work. (And I can't see how that could be implemented anyway.)

所以它是一个神奇的内置运算符?

So it is a magic built-in operator?

(我相信我之前在 SO 上看到过这个问题,但无法搜索...)

(I believe I have seen this question on SO before, but it's impossible to search for...)

推荐答案

是的,管道 (|) 是用于模式匹配的内置工具(请参阅 Scala 语言参考).模式匹配部分(第 8 节)在 8.1.11 节中定义了所谓的模式替代.定义说:

Yes the pipe (|) is a built-in for pattern matching (see the scala language reference). The Pattern matching section (section 8) defines in section 8.1.11 what is called Pattern Alternatives. The definition says:

模式替代 p1 |... |pn由许多替代方案组成模式 pi .所有替代模式类型检查与预期图案的类型.他们可能没有绑定通配符以外的变量.这替代模式匹配值 v如果至少有一个它的替代品匹配 v.

A pattern alternative p1 | ... | pn consists of a number of alternative patterns pi . All alternative patterns are type checked with the expected type of the pattern. They may no bind variables other than wildcards. The alternative pattern matches a value v if at least one its alternatives matches v.

是的,管道是内置的,对模式匹配上下文敏感.

So yes, the pipe is a built-in that is context sensitive to pattern matching.

这篇关于如何|(管道)在模式匹配工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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