home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / gofer230.zip / Progs / Gofer / Demos / stack.gs < prev    next >
Text File  |  1994-06-23  |  1KB  |  53 lines

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