home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / gofer230.zip / Progs / Gofer / Demos / Ccexamples / abstack.lgs next >
Text File  |  1994-06-23  |  2KB  |  84 lines

  1. ------------------------------------------------------------------------------
  2. Another, rather different application of constructor classes, described
  3. to me by Stuart Clayman:
  4.  
  5. I may want to implement a stack using different mechanisms, namely
  6. built in list type, or my own contructor.  Type classes don't allow
  7. this, but constructor classes do. Consider this:
  8.  
  9. >   class Stack s where
  10. >    push  :: a -> s a -> s a
  11. >    pop   :: s a -> s a
  12. >    top   :: s a -> a
  13. >    empty :: s a
  14. >
  15. >   instance Stack [] where
  16. >    push v s = v:s
  17. >    pop (t:s) = s
  18. >    top (t:s) = t
  19. >    empty = []
  20. >
  21. >   teststack :: Stack s => s Int
  22. >   teststack  = push 5 (push 4 (push 3 (push 2 (push 1 empty))))
  23.  
  24. This defines a stack of things.  Now we can instantiate it:
  25.  
  26. >   stack1 :: [Int]
  27. >   stack1 = teststack
  28.  
  29. to give a stack implemented as a list.  If we want to use our own
  30. constructor we can do this
  31.  
  32. >   data List a = Nil | Cons a (List a)
  33. >
  34. >   instance Stack List where
  35. >    push v s = Cons v s
  36. >    pop (Cons t s) = s
  37. >    top (Cons t s) = t
  38. >    empty = Nil
  39. >
  40. >   stack2 :: List Int
  41. >   stack2 = teststack
  42.  
  43. to give a different sort of stack.  In this way we can overload
  44. operators to any construct.  The use of restricted types can hide
  45. the real types of [Int] and List Int in stack1 and stack2.
  46.  
  47. How about the following for a stack of numerics:
  48.  
  49. >   newteststack :: (Num a,Stack s) => s a
  50. >   newteststack  = foldr push empty (map fromInteger [5,4,3,2,1])
  51.  
  52. This can be instantiated in several different ways.  Generic stacks of
  53. integers or floats:
  54.  
  55. >   inewstack :: Stack s => s Int
  56. >   inewstack  = newteststack
  57.  
  58. >   fnewstack :: Stack s => s Float
  59. >   fnewstack  = newteststack
  60.  
  61. List or [] stacks of generic numbers:
  62.  
  63. >   lnewstack1 :: Num a => [a]
  64. >   lnewstack1  = newteststack
  65.  
  66. >   lnewstack2 :: Num a => List a
  67. >   lnewstack2  = newteststack
  68.  
  69. Or specific stack/number combinations:
  70.  
  71. >   ilnewstack1 :: [Int]
  72. >   ilnewstack1  = newteststack
  73.  
  74. >   ilnewstack2 :: List Int
  75. >   ilnewstack2  = newteststack
  76.  
  77. >   flnewstack1 :: [Float]
  78. >   flnewstack1  = newteststack
  79.  
  80. >   flnewstack2 :: List Float
  81. >   flnewstack2  = newteststack
  82.  
  83. ------------------------------------------------------------------------------
  84.