fork download
  1. {-# LANGUAGE ExistentialQuantification #-}
  2.  
  3. data Square = Square Int
  4. data Circle = Circle Int
  5. data Rectangle = Rectangle Int Int
  6.  
  7. class HasArea a where
  8. area :: a -> Double
  9.  
  10. instance HasArea Square where
  11. area (Square n) = fromIntegral n * fromIntegral n
  12.  
  13. instance HasArea Circle where
  14. area (Circle r) = pi * fromIntegral r
  15.  
  16. instance HasArea Rectangle where
  17. area (Rectangle n m) = fromIntegral n * fromIntegral m
  18.  
  19. data Shape = forall s. HasArea s => Shape s
  20.  
  21. shapes :: [Shape]
  22. shapes = [Shape (Square 5), Shape (Circle 2), Shape (Rectangle 10 5)]
  23.  
  24. shapeArea :: Shape -> Double
  25. shapeArea (Shape s) = area s
  26.  
  27. main = print $ map shapeArea shapes
Success #stdin #stdout 0s 6264KB
stdin
Standard input is empty
stdout
[25.0,6.283185307179586,50.0]