Difference between revisions of "Existential type"

From HaskellWiki
Jump to navigation Jump to search
 
Line 1: Line 1:
  +
Existential types in conjunction with type classes can be used to emulate the dynamic dispatch mechanism of object oriented programming languages. To illustrate this concept I show how a classic example from object oriented programming can be encoded in Haskell.
  +
  +
 
data Shape = forall a. Shape_ a => Shape a
 
data Shape = forall a. Shape_ a => Shape a
 
 

Revision as of 05:39, 22 February 2006

Existential types in conjunction with type classes can be used to emulate the dynamic dispatch mechanism of object oriented programming languages. To illustrate this concept I show how a classic example from object oriented programming can be encoded in Haskell.


data Shape = forall a. Shape_ a => Shape a

type Radius = Double
type Side   = Double


data Circle    = Circle    Radius
data Rectangle = Rectangle Side Side
data Square    = Square    Side

class Shape_ a where
  perimeter :: a -> Double
  area      :: a -> Double

instance Shape_ Circle where
  perimeter (Circle r) = 2 * pi * r
  area      (Circle r) = pi * r * r

instance Shape_ Rectangle where
  perimeter (Rectangle x y) = 2*(x + y)
  area      (Rectangle x y) = x * y

instance Shape_ Square where
  perimeter (Square s) = 4*s
  area      (Square s) = s*s

instance Shape_ Shape where
  perimeter (Shape shape) = perimeter shape
  area      (Shape shape) = area      shape


--
-- Smart constructors
--

circle :: Radius -> Shape
circle r = Shape (Circle r)

rectangle :: Side -> Side -> Shape
rectangle x y = Shape (Rectangle x y)

square :: Side -> Shape
square s = Shape (Square s)

shapes :: [Shape]
shapes = [circle 2.4, rectangle 3.1 4.4, square 2.1]