Skip to content

Instantly share code, notes, and snippets.

@7shi
Forked from shigemk2/AlgebraCalculation.scala
Last active August 29, 2015 14:23
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 7shi/92d4d3b4cf317e8a2f18 to your computer and use it in GitHub Desktop.
Save 7shi/92d4d3b4cf317e8a2f18 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() => ""
case Add(x) => str(x)
case Add(x, xs@_*) => str(x) ++ "+" ++ str(Add(xs: _*))
}
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