Created
June 29, 2015 14:16
-
-
Save shigemk2/8b384adfa1efe2b9aad6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
sealed trait Expr | |
case class N(n: Int) extends Expr | |
case class Add(n: Expr*) extends Expr | |
case class Mul(n: Expr*) extends Expr | |
def str(e: Expr): String = e match { | |
case N(x) => x.toString | |
case Add(xs @_*) if xs.isEmpty => "" | |
case Add(xs @_*) if xs.length == 1 => str(xs.head) | |
case Add(xs @_*) if isneg(xs(1)) => str(xs.head) ++ str(Add(xs.tail)) | |
case Add(xs @_*) => str(xs.head) ++ "+" ++ str(Add(xs.tail)) | |
} | |
def isneg(e: Expr): Boolean = e match { | |
case N(n) if n < 0 => true | |
case _ => false | |
} | |
println(str(N(1)) == "1") | |
println(str(Add(N(1),N(2))) == "1+2") | |
// println(eval(Add(List(N(2),N(3)))) == 2+3) | |
// println(eval(Add(List(N(5),N(-3)))) == 5-3) | |
// println(eval(Mul(List(N(3),N(4)))) == 3*4) | |
// println(eval(Add(List(N(1),Mul(List(N(2),N(3)))))) == 1+2*3) | |
// println(eval(Mul(List(Add(List(N(1),N(2))),N(3)))) == (1+2)*3) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment