scala – pattern guard

def simplifyAdd(e: Expr) = e match {

case BinOp(“+”, x, x) => BinOp(“*”, x, Number(2)) case _ => e }

<console>:11: error: x is already defined as value x case BinOp(“+”, x, x) => BinOp(“*”, x, Number(2))

This fails, because Scala restricts patterns to be linear: a pattern variable mayonlyappearonceinapattern. However,youcanre-formulatethematch with a pattern guard

 

def simplifyAdd(e: Expr) = e match { case BinOp(“+”, x, y) if x == y => BinOp(“*”, x, Number(2)) case _ => e }