Motivation for match expression syntax

大兔子大兔子 提交于 2019-12-13 14:08:58

问题


The syntax for match expressions is pretty nice:

expr match {
    case Test(l1) => ...
    ...
}

But it's driving me nuts that I don't understand the motivation to why this this syntax is used instead of match (expr) ..., like branching statements in a decent C descendant!

I see no reasonably explanation for this. And I don't find the answer neither in Programming in Scala, the Scala web site, in this paper, this thesis, here on SO nor on the rest of the web.

It's not that it's anything wrong with it, just that it's a complete mystery. And when match work in this way, why not if and for also?

Does anybody know? I don't think I can stand using the language any longer without finding this out. I think about it all the time. I can hardly sleep at night.


回答1:


To take a similar bit of Scala syntax, guards in pattern matching cases don't require parentheses around their conditional expressions—e.g., the following:

case i if i % 2 == 0 => i / 2

Is just as valid as this:

case i if (i % 2 == 0) => i / 2

Sticking to the C-family style would mean requiring the latter form, even though the parentheses aren't necessary for disambiguation. The Scala language designers decided that reducing line noise trumped maintaining the family resemblance in this case.

I'd guess that a similar motivation is at work in the match syntax, and to my eye match (expr) { ... } does indeed look pretty awful (and misleading) compared to expr match { ... }.

Also, just this afternoon I refactored someone else's x match { ... } on an Option to x map { ... } instead. match as an infix operator makes the similarity between these two expressions clear.

On the issue of why match isn't just a method, here's a five year-old question from David Pollak on the scala-debate mailing list:

Why is 'match' a language level construct rather than a method on Any?

And Martin Odersky's answer:

It used to be that way in Scala 1. I am no longer sure why we changed. syntax highlighting? error reporting? not sure. I don't think it matters much either way, though.

I'm with Martin on this one.

Note that there are a couple of practical differences (apart from the simple "dot or not" question). For example, this doesn't compile:

def foo[A, B](f: PartialFunction[A, B])(a: A) = a match f

If match were still a method on Any, requiring a literal bunch of cases would be a rather strange requirement.



来源:https://stackoverflow.com/questions/17799024/motivation-for-match-expression-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!