Added a queue implementation

Added a queue to the stdlib and a test case for it.
This commit is contained in:
Marcus Godwin
2015-08-28 23:46:30 -04:00
parent cc9cad8060
commit 6d7113e41f
3 changed files with 176 additions and 0 deletions

70
stdlib/queue.krak Normal file
View File

@@ -0,0 +1,70 @@
import stack
import serialize
import vector
fun queue<T>() : queue<T> {
var out.construct() : queue<T>
return out
}
obj queue<T> (Object, Serializable) {
var stack1 : stack::stack<T>
var stack2 : stack::stack<T>
fun construct(): *queue<T> {
stack1.construct()
stack2.construct()
return this
}
fun copy_construct(other : *queue<T>) {
stack1.copy_construct(&other->stack1)
stack2.copy_construct(&other->stack2)
}
fun destruct() {
stack1.destruct()
stack2.destruct()
}
fun operator=(other : ref queue<T>) {
stack1 = other.stack1
stack2 = other.stack2
}
fun serialize() : vector::vector<char> {
return serialize::serialize(stack1)+serialize::serialize(stack2)
}
fun unserialize(it : ref vector::vector<char>, pos : int) : int {
pos = stack1.unserialize(it,pos)
pos = stack2.unserialize(it,pos)
return pos
}
fun push(it : ref T) {
stack1.push(it)
}
fun pop() : T {
if(stack2.empty()) {
while(!stack1.empty()) {
stack2.push(stack1.pop())
}
}
return stack2.pop()
}
fun clear() {
stack1.clear()
stack2.clear()
}
fun size() : int {
return stack1.size()+stack2.size()
}
fun empty() : bool {
return ((stack1.size()+stack2.size()) == 0)
}
}

View File

@@ -0,0 +1,67 @@
adding to q
pushing...
0
pushing...
1
pushing...
2
pushing...
3
pushing...
4
pushing...
5
pushing...
6
pushing...
7
pushing...
8
pushing...
9
adding to q2
pushing...
9
pushing...
8
pushing...
7
pushing...
6
pushing...
5
pushing...
4
pushing...
3
pushing...
2
pushing...
1
pushing...
0
pop test...
0
q is about to pop
q popped
q2 is about to pop
9
8
7
6
5
4
3
2
1
0
1
2
3
4
5
6
7
8
9
done

39
tests/test_queue.krak Normal file
View File

@@ -0,0 +1,39 @@
import queue
import io:*;
fun main() : int {
var q.construct() : queue::queue<int>
var q2.construct() : queue::queue<int>
println("adding to q")
for(var i = 0; i < 10; i++;) {
defer println(i)
println("pushing...")
q.push(i)
}
println("adding to q2")
for(var i = 9; i >= 0; i--;) {
defer println(i)
println("pushing...")
q2.push(i)
}
println("pop test...")
println(q.pop())
println("q is about to pop")
while(!q.empty()) {
q2.push(q.pop())
}
println("q popped")
println("q2 is about to pop")
while(!q2.empty()) {
println(q2.pop())
}
println("done")
return 0
}