RosettaCodeData/Task/Stack/CLU/stack.clu

56 lines
1.3 KiB
Plaintext

% Stack
stack = cluster [T: type] is new, push, pop, peek, empty
rep = array[T]
new = proc () returns (cvt)
return (rep$new())
end new
empty = proc (s: cvt) returns (bool)
return (rep$size(s) = 0)
end empty;
push = proc (s: cvt, val: T)
rep$addh(s, val)
end push;
pop = proc (s: cvt) returns (T) signals (empty)
if rep$empty(s)
then signal empty
else return(rep$remh(s))
end
end pop
peek = proc (s: cvt) returns (T) signals (empty)
if rep$empty(s)
then signal empty
else return(s[rep$high(s)])
end
end peek
end stack
start_up = proc ()
po: stream := stream$primary_output()
% Make a stack
s: stack[int] := stack[int]$new()
% Push 1..10 onto the stack
for i: int in int$from_to(1, 10) do
stack[int]$push(s, i)
end
% Pop items off the stack until the stack is empty
while ~stack[int]$empty(s) do
stream$putl(po, int$unparse(stack[int]$pop(s)))
end
% Trying to pop off the stack now should raise 'empty'
begin
i: int := stack[int]$pop(s)
stream$putl(po, "Still here! And I got: " || int$unparse(i))
end except when empty:
stream$putl(po, "The stack is empty.")
end
end start_up