From 1dc768ae51f25995ae4c6a28d303a3cf09087ae6 Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Tue, 11 Mar 2025 15:46:12 +0100 Subject: [PATCH] added assignment 4 ex 1 --- src/Assignment4/Ex1_Expressions.sc | 60 ++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 src/Assignment4/Ex1_Expressions.sc diff --git a/src/Assignment4/Ex1_Expressions.sc b/src/Assignment4/Ex1_Expressions.sc new file mode 100644 index 0000000..702425c --- /dev/null +++ b/src/Assignment4/Ex1_Expressions.sc @@ -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) \ No newline at end of file