-
Notifications
You must be signed in to change notification settings - Fork 2
/
Stack.scala
52 lines (42 loc) · 1.22 KB
/
Stack.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package dataStructures
import dataStructures.miscellaneous.DataStructuresExceptionMessages.EmptyStackException
import dataStructures.miscellaneous.DataStructureException
/**
* Contains functional realisation of a standard stack.
*
* https://en.wikipedia.org/wiki/Stack_(abstract_data_type)
*
* Purity project by Daniil Tekunov.
*/
class Stack[+A](inPart: List[A] = Nil) {
/**
* Checks, whether the stack is empty.
*/
def isEmpty: Boolean = inPart match {
case Nil => true
case _ => false
}
/**
* Adds an element to a stack.
*/
def add[B >: A](element: B): Stack[B] = new Stack(element :: inPart)
/**
* Removes an element from a queue.
*/
def remove: (A, Stack[A]) = inPart match {
case outcomeElement :: tail => (outcomeElement, new Stack(tail))
case Nil => throw new DataStructureException(EmptyStackException)
}
/**
* Takes the first element from a queue.
*/
def first: A = inPart match {
case element :: tail => element
case Nil => throw new DataStructureException(EmptyStackException)
}
/**
* Returns the tail of a stack.
*/
def init: Stack[A] = new Stack(inPart.tail)
}
object Stack { def createEmptyStack[A]: Stack[A] = new Stack() }