Skip to content

Instantly share code, notes, and snippets.

@veve90
Created August 17, 2016 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save veve90/2798b268e315ed79bc5500eb6b62f6e7 to your computer and use it in GitHub Desktop.
Save veve90/2798b268e315ed79bc5500eb6b62f6e7 to your computer and use it in GitHub Desktop.
LearningScala|week4.6 |Functional Programming Principles in Scala
trait Expr
case class Number(n:Int) extends Expr
case class Sum(n:Expr,m:Expr) extends Expr
case class Var(n:String) extends Expr
case class Prod(n:Expr,m:Expr) extends Expr
def eval(e:Expr):Int = e match {
case Number(n) => n
case Sum(x,y) => eval(x) + eval(y)
case Prod(x,y) => eval(x) * eval(y)
}
def show(e: Expr): String = e match {
case Number(n) => n.toString
case Sum(x, y) => {
show(x) + "+" + show(y)
}
case Prod(l, r) => {
if (l.isInstanceOf[Sum]) {
"("+show(l) + ")*" + show(r)
}else if (r.isInstanceOf[Sum]) {
show(l) + "*(" + show(r)+")"
}else{
show(l) + "*" + show(r)
}
}
case Var(x) => x
}
println("Result Here")
println(show(Sum(Number(1), Number(44))));
// (1+44)*2
println(show(Prod(Sum(Number(1), Number(44)),Number(2))));
// 1*44+2
println(show(Sum(Prod(Number(1), Number(44)),Number(2))));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment