Skip to content

Instantly share code, notes, and snippets.

@shigemk2
Created June 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save shigemk2/8b384adfa1efe2b9aad6 to your computer and use it in GitHub Desktop.
Save shigemk2/8b384adfa1efe2b9aad6 to your computer and use it in GitHub Desktop.
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