From f693d693661c60ff4f870636d6de47a7074ce43e Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Tue, 15 Apr 2025 15:59:16 +0200 Subject: [PATCH] added assignment 7 ex 1 --- src/Assignment7/Ex1.sc | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/Assignment7/Ex1.sc diff --git a/src/Assignment7/Ex1.sc b/src/Assignment7/Ex1.sc new file mode 100644 index 0000000..c2f24db --- /dev/null +++ b/src/Assignment7/Ex1.sc @@ -0,0 +1,35 @@ +trait Stack[+A] { + def push[B >: A](elem: B) : Stack[B] = ElemStack(elem, this) + def top: A + def pop: Stack[A] +} + +case class EmptyStack[+A]() extends Stack[A] { + override def top: A = throw new IndexOutOfBoundsException("Stack is empty") + override def pop: Stack[A] = this +} + +case class ElemStack[+A](elmt: A, base: Stack[A]) extends Stack[A] { + override def top: A = elmt + override def pop: Stack[A] = base + override def toString: String = elmt.toString + "," + base.toString +} + +// Construction, pop and toString +val a = EmptyStack().push("hello").push("world").push("it's fun").pop +assert(a.toString() == "world,hello,EmptyStack()") + +// Getting top +val b = EmptyStack().push(1).push(3) +assert(b.top == 3) + +// Variance checks +class Foo +class Bar extends Foo +val c: Stack[Bar] = EmptyStack().push(new Bar()).push(new Bar()) +assert(c.top.isInstanceOf[Bar] == true) +assert(c.top.isInstanceOf[Foo] == true) + +// Variance check 2 +val d: Stack[Foo] = EmptyStack().push(new Bar()).push(new Bar()) +assert(d.top.isInstanceOf[Foo]) \ No newline at end of file