KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
In particular with respect to pattern matching and case classes. Consider the following: abstract class Expr case class Var(name: String) extends Expr case class Number(num: Double) extends Expr case class UnOp(operator: String, arg: Expr) extends Expr case class BinOp(operator: String, left: Expr, right: Expr) extends Expr object Expr { def simplify(expr: Expr): Expr = expr match { // Some basic simplification rules... case UnOp("-", UnOp("-", e)) => simplify(e) // Double negation case BinOp("+", e, Number(0)) => simplify(e) // Adding zero case BinOp("-", e, Number(0)) => simplify(e) // Subtracting zero case BinOp("*", e, Number(1)) => simplify(e) // Multiplying by one case BinOp("*", e, Number(0)) => Number(0) // Multiplying by zero case _ => expr // Default, could not simplify given above rules } } Given any sample call, say, simplify(UnOp("-", UnOp("-", UnOp("-", UnOp("-", Var("x")))))) (which results in Var("x") ), does the order of the alternatives in the match expression matter for performance? Side note, kind of related (my own observation): One thing that really strikes me about simplify is that it is a recursive function, although unlike other recursive functions I've written / dealt with, the base case comes last in order to avoid terminating early.
Tags (comma-separated)
Save Edits
Cancel