racket/collects/honu/examples/Stack.honu
2005-05-27 18:56:37 +00:00

81 lines
1.4 KiB
Plaintext

type IStack
{
void push (Any elt);
Any pop();
bool empty();
IStack copy();
}
class ListStack() : IStack impl IStack {
List stack = new MTList();
void push (Any elt) {
stack = new ConsList(car = elt, cdr = stack);
}
Any pop() {
if stack.empty() {
error("The stack is empty!");
} else {
Any x = stack.first();
stack = stack.drop(1);
return x;
};
}
bool empty() {
return stack.empty();
}
IStack copy() {
List tocopy = stack.reverse();
IStack newStack = new ListStack();
while(!tocopy.empty()) {
newStack.push(tocopy.first());
tocopy = tocopy.drop(1);
};
return newStack;
}
export IStack : push, pop, empty, copy;
}
type ICountedStack <: IStack
{
int numElements();
}
mixin addCount() : ICountedStack at IStack impl ICountedStack
{
int numElts = 0;
super();
void countedPush(Any elt)
{
numElts = numElts + 1;
push(elt);
}
Any countedPop()
{
Any x = pop();
numElts = numElts - 1;
return x;
}
int getSize()
{
numElts;
}
export ICountedStack :
countedPush as push,
countedPop as pop,
empty,
copy, // but this isn't a countable stack!
getSize as numElements;
}
subclass CountedListStack = addCount(ListStack);