added assignment 7 ex 1

This commit is contained in:
Louis Heredero 2025-04-15 15:59:16 +02:00
parent d8b22157c5
commit f693d69366
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7

35
src/Assignment7/Ex1.sc Normal file
View File

@ -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])