added assignment 7 ex 1
This commit is contained in:
parent
d8b22157c5
commit
f693d69366
35
src/Assignment7/Ex1.sc
Normal file
35
src/Assignment7/Ex1.sc
Normal 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])
|
Loading…
x
Reference in New Issue
Block a user