当前位置: 动力学知识库 > 问答 > 编程问答 >

Why does Scala require pattern variables to be linear?

问题描述:

Scala requires pattern variables to be linear, i.e. pattern

variable may not occur more than once in a pattern. Thus, this example does not compile:

def tupleTest(tuple: (Int, Int)) = tuple match {

case (a, a) => a

case _ => -1

}

But you can use two pattern variables and a guard to check equality instead:

def tupleTest(tuple: (Int, Int)) = tuple match {

case (a, b) if a == b => a

case _ => -1

}

So why does Scala require pattern variables to be linear? Are there any cases that can not be transformed like this?

Edit

It is easy to transform the first example into the second (Scala to Scala). Of all occurrences of a variable v in the pattern take the expressions that is evaluated first and assign it to the variable v. For each other occurrence introduce a new variable with a name that is not used in the current scope. For each of those variables v' add a guard v == v'. It is the same way a programmer would go (=> same efficiency). Is there any problem with this approach? I'd like to see an example that can not be transformed like this.

网友答案:

Because case (a, b) is basically assigning val a to _._1 and val b to _._2 (at least you can view it like that). In case of case (a, a), you cannot assign val a to both _._1 and _._2.

Actually the thing you want to do would have been looked like

case (a, `a`) => ???

as scala uses backtick to match an identifier. But unfortunately that still doesn't work as the visibility of a is given only after => (would have been fun though, I also hate writing case (a, b) if a = b =>). And the reason of this is probably just because it is harder to write a compiler that supports that

分享给朋友:
您可能感兴趣的文章:
随机阅读: