Pagini
Workshops
Parteneri
Today we cover pattern matching, one of Scala's most powerful features.
You can find today's contents here.
Let us have a simple hierarchy for dealing with mathematical expressions:
trait Expr case class Number(n: Int) extends Expr case class Sum(e1: Expr, e2: Expr) extends Expr
Expr
to a human readable String, e.g. 1 + 2
:def show(e: Expr): String
Prod
.Sum(Prod(Number(2), Number(1)), Number(3)).show
should return “2 * 1 + 3”
.Prod(Sum(Number(2), Number(1)), Number(3)).show
should return “(2 + 1) * 3”
.Var
which takes a String as a parameter.show
function you have just created.def eval(vars: Map[String,Int]): Int
which returns the numerical value of the mathematical expression.
The vars
parameter denotes all the variable name-value associations so you could replace Var
s with their corresponding numerical value.
If a variable cannot be found in the map, consider it to be 0.
eval
recursively