匹配是一种语言特征吗?
我正在自学 Scala,我有一个哲学问题。模式匹配是 Scala 的语言功能,还是只是一个库功能?换句话说,如果我足够熟练的话,我是否可以编写 xmatch
,一个除了名称之外在各个方面都与 match
相同的函数?实际上,我认为这是两个略有不同的问题:是否匹配库功能,以及它是否可以是库功能?
我正在考虑尝试重写比赛,纯粹作为练习,但我想要一些保证这是可能的。
I'm teaching myself Scala and I have sort of a philosophical question. Is pattern matching a language feature of Scala, or just a library feature? To put it another way, could I, were I sufficiently skilled, write xmatch
, a function that was identical to match
in every way except the name? Actually, I think those are two slightly different questions: is matching a library feature, and could it be a library feature?
I was thinking of trying to re-write match, purely as an exercise, but I wanted some assurance it was possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
模式匹配是一种语言功能,其中
match
语句只是最显着的示例。以下是另外两个常用的示例:所以,不,您不能自己这样做。该语言不允许您定义创建变量的新方法,因此这些事情只能在语言支持的情况下发生。
match 语句本身使用语言内部的模式匹配变量创建支持,但原则上可以作为库功能实现。然而,在某些情况下它的效率会很低:
所以,总而言之,不,你不能自己编写模式匹配,虽然你可以编写匹配语句,但使用现有的有一些优点。
Pattern matching is a language feature, of which the
match
statement is only the most notable example. Here are two other commonly-used examples:So, no, you can't do that on your own. The language does not allow you to define new ways to create variables, so these things can only happen with language support.
The
match
statement itself uses the pattern-matching variable-creation support inside the language, but otherwise could in principle be implemented as a library feature. However, it would be inefficient in several cases:So, all in all, no, you can't write pattern matching yourself, and while you could write the match statement, there are advantages in using the existing one.
事实上,我听说
match
曾经是在库中实现的。 Scala 参考中的更改日志表明match
在 2.0 版本中成为保留关键字,此时object.match { ... }
也不再是有效语法。原则上实现它相当容易:
我不知道它停止以这种方式实现的确切原因。
Actually,
match
used to be implemented in the library, I've heard. The Change Log in the Scala Reference indicatesmatch
became a reserved keyword on version 2.0, at which pointobject.match { ... }
ceased to be a valid syntax as well.It is rather easy to implement it in principle:
I don't know the exact reasons why it ceased to be implemented this way.
模式匹配绝对是一种语言特性。也就是说,因为在 Scala 中编写控制流结构非常简单(并且模式匹配非常强大),所以您可以轻松编写自己的
match
(与其他语言相比)。另一方面,
match
仍然是语言核心的一部分(我认为),但它的行为更像是库中的东西。由于模式匹配的强大功能,它感觉如此有机。也就是说,是的,您绝对可以重写
match
。Pattern matching is definitely a language feature. That said, because writing control flow structures in Scala is so easy (and pattern matching is robust), you could easily write your own
match
(compared to other languages).match
, on the other hand, is still a part of the language core (I think), but it behaves much more like something in the library. It feels so organic because of how powerful pattern matching is.That said, yeah, you could definitely rewrite
match
.