-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.hs
55 lines (36 loc) · 1.25 KB
/
Stack.hs
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
module Stack(Stack,push,pop,top,emptyStack,stackEmpty) where
emptyStack:: Stack a
stackEmpty:: Stack a -> Bool
push :: a-> Stack a -> Stack a
pop :: Stack a -> Stack a
top :: Stack a -> a
{- implementation with a constructor type -}
data Stack a = EmptyStk
| Stk a (Stack a)
instance (Show a) => Show (Stack a) where
showsPrec p EmptyStk str = showChar '-' str
showsPrec p (Stk x s) str = shows x (showChar '|' (shows s str))
emptyStack = EmptyStk
stackEmpty EmptyStk = True
stackEmpty _ = False
push x s = Stk x s
pop EmptyStk = error "pop from an empty stack"
pop (Stk _ s) = s
top EmptyStk = error "top from an empty stack"
top (Stk x _) = x
{- end of implementation with a constructor type-}
{- list implementation
newtype Stack a = Stk [a]
instance (Show a) => Show (Stack a) where
showsPrec p (Stk []) str = showChar '-' str
showsPrec p (Stk (x:xs)) str
= shows x (showChar '|' (shows (Stk xs) str))
emptyStack = Stk []
stackEmpty (Stk []) = True
stackEmpty (Stk _ ) = False
push x (Stk xs) = Stk (x:xs)
pop (Stk []) = error "pop from an empty stack"
pop (Stk (_:xs)) = Stk xs
top (Stk []) = error "top from an empty stack"
top (Stk (x:_)) = x
end of list implementation -}