Created
August 17, 2016 08:53
-
-
Save veve90/2798b268e315ed79bc5500eb6b62f6e7 to your computer and use it in GitHub Desktop.
LearningScala|week4.6 |Functional Programming Principles in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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