summaryrefslogtreecommitdiff
path: root/week3/mart/StdStack.icl
blob: 13220e12dc8f88b98e215dc9fe6d210621fc2cdb (plain) (blame)
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
53
54
55
56
57
implementation module StdStack

import StdEnv

:: Stack a = Stack [a]

newStack :: Stack a
newStack = Stack []

push     ::  a  (Stack a) -> Stack a
push x (Stack xs) = Stack [x:xs]

pushes   :: [a] (Stack a) -> Stack a
pushes [] (Stack s) = Stack s
pushes [x:xs] (Stack s) = pushes xs (push x (Stack s))

pop      ::     (Stack a) -> Stack a
pop (Stack []) = abort "Can't pop from empty stack..."
pop (Stack [x:xs]) = Stack xs

popn     :: Int (Stack a) -> Stack a
popn 0 s = s
popn n s = popn (n-1) (pop s)

top      ::     (Stack a) -> a
top (Stack []) = abort "Can't give top of empty stack..."
top (Stack [x:_]) = x

topn     :: Int (Stack a) -> [a]
topn 0 _ = []
topn n x = [top x:topn (n-1) (pop x)]

elements ::     (Stack a) -> [a]
elements (Stack s) = s

count    ::     (Stack a) -> Int
count (Stack []) = 0
count (Stack [_:xs]) = 1 + count (Stack xs)

Start  = ( "s0 = newStack = ",        s0,'\n'
         , "s1 = push 1 s0 = ",       s1,'\n'
         , "s2 = pushes [2..5] s1 = ",s2,'\n'
         , "s3 = pop s2 = ",          s3,'\n'
         , "s4 = popn 3 s3 = ",       s4,'\n'
         , "s5 = top s4 = ",          s5,'\n'
         , "s6 = topn 3 s2 = ",       s6,'\n'
         , "s7 = elements s2 = ",     s7,'\n'
         )
where
	s0 = newStack
	s1 = push 1 s0
	s2 = pushes [2..5] s1
	s3 = pop s2
	s4 = popn 3 s3
	s5 = top s4
	s6 = topn 3 s2
	s7 = elements s2