-
-
Save 7shi/92d4d3b4cf317e8a2f18 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() => "" | |
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