added assignment 4 ex 1
This commit is contained in:
parent
a608a602ad
commit
1dc768ae51
60
src/Assignment4/Ex1_Expressions.sc
Normal file
60
src/Assignment4/Ex1_Expressions.sc
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
sealed abstract class Expr
|
||||||
|
case class Number(n: Int) extends Expr
|
||||||
|
case class Sum(e1: Expr, e2: Expr) extends Expr
|
||||||
|
case class Product(e1: Expr, e2: Expr) extends Expr
|
||||||
|
|
||||||
|
def eval(e: Expr): Int = e match {
|
||||||
|
case Number(n) => n
|
||||||
|
case Sum(e1, e2) => eval(e1) + eval(e2)
|
||||||
|
case Product(e1, e2) => eval(e1) * eval(e2)
|
||||||
|
}
|
||||||
|
|
||||||
|
def show(e: Expr): String = e match {
|
||||||
|
case Number(n) => n.toString
|
||||||
|
case Sum(e1, e2) => show(e1) + " + " + show(e2)
|
||||||
|
case Product(e1, e2) => {
|
||||||
|
val left: String = e1 match {
|
||||||
|
case Sum(e1a, e1b) => "(" + show(e1) + ")"
|
||||||
|
case _ => show(e1)
|
||||||
|
}
|
||||||
|
val right: String = e2 match {
|
||||||
|
case Sum(e2a, e2b) => "(" + show(e2) + ")"
|
||||||
|
case _ => show(e2)
|
||||||
|
}
|
||||||
|
left + " * " + right
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val e1: Expr = Sum(Number(1), Sum(Number(2), Number(3)))
|
||||||
|
eval(e1)
|
||||||
|
show(e1)
|
||||||
|
|
||||||
|
val e2: Expr = Sum(
|
||||||
|
Number(2),
|
||||||
|
Product(
|
||||||
|
Number(3),
|
||||||
|
Sum(
|
||||||
|
Number(4),
|
||||||
|
Number(5)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
eval(e2)
|
||||||
|
show(e2)
|
||||||
|
|
||||||
|
|
||||||
|
val expr0 = Sum(Product(Number(2), Number(3)), Number(4))
|
||||||
|
println("Expr0: " + show(expr0)) // Expr0: 2*3+4
|
||||||
|
assert(eval(expr0) == 10)
|
||||||
|
|
||||||
|
val expr1 = Product(Number(4), Number(12))
|
||||||
|
println("Expr1: " + show(expr1)) // Expr1: 4*12
|
||||||
|
assert(eval(expr1) == 48)
|
||||||
|
|
||||||
|
val expr2 = Product(Sum(Number(2), Number(3)), Number(4))
|
||||||
|
println("Expr2: " + show(expr2)) // Expr2: (2+3)*4
|
||||||
|
assert(eval(expr2) == 20)
|
||||||
|
|
||||||
|
val expr3 = Product(Number(2), Sum(Number(3), Number(4)))
|
||||||
|
println("Expr3: " + show(expr3)) // Expr3: 2*(3+4)
|
||||||
|
assert(eval(expr3) == 14)
|
Loading…
x
Reference in New Issue
Block a user