home *** CD-ROM | disk | FTP | other *** search
/ PSION CD 2 / PsionCDVol2.iso / Programs / 876 / hugs.sis / Stack.hs < prev    next >
Encoding:
Text File  |  2000-09-21  |  1.2 KB  |  55 lines

  1. -- Stacks: using restricted type synonyms
  2.  
  3. module Stack where
  4.  
  5. type Stack a = [a] in emptyStack, push, pop, topOf, isEmpty
  6.  
  7. emptyStack :: Stack a
  8. emptyStack  = []
  9.  
  10. push       :: a -> Stack a -> Stack a
  11. push        = (:)
  12.  
  13. pop        :: Stack a -> Stack a
  14. pop []      = error "pop: empty stack"
  15. pop (_:xs)  = xs
  16.  
  17. topOf      :: Stack a -> a
  18. topOf []    = error "topOf: empty stack"
  19. topOf (x:_) = x
  20.  
  21. isEmpty    :: Stack a -> Bool
  22. isEmpty     = null
  23.  
  24. instance Eq a => Eq (Stack a) where
  25.     s1 == s2 | isEmpty s1 = isEmpty s2
  26.              | isEmpty s2 = isEmpty s1
  27.              | otherwise  = topOf s1 == topOf s2 && pop s1 == pop s2
  28.  
  29. -- A slightly different presentation:
  30.  
  31. type Stack' a = [a] in
  32.    emptyStack' :: Stack' a,
  33.    push'       :: a -> Stack' a -> Stack' a,
  34.    pop'        :: Stack' a -> Stack' a,
  35.    topOf'      :: Stack' a -> a,
  36.    isEmpty'    :: Stack' a -> Bool
  37.  
  38. emptyStack'  = []
  39.  
  40. push'        = (:)
  41.  
  42. pop' []      = error "pop': empty stack"
  43. pop' (_:xs)  = xs
  44.  
  45. topOf' []    = error "topOf': empty stack"
  46. topOf' (x:_) = x
  47.  
  48. isEmpty'     = null
  49.  
  50. instance Eq a => Eq (Stack' a) where
  51.     s1 == s2 | isEmpty' s1 = isEmpty' s2
  52.              | isEmpty' s2 = isEmpty' s1
  53.              | otherwise   = topOf' s1 == topOf' s2 && pop' s1 == pop' s2
  54.  
  55.