Want more features on Pastebin? Sign Up, it's FREE!

HeterogeneousListOfShapes.hs

By: jckuri on Feb 7th, 2013  |  syntax: Haskell  |  size: 0.88 KB  |  views: 75  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. {-# LANGUAGE GADTs #-}
  2.  
  3. class Shape s where
  4.  area :: s -> Double
  5.  perimeter :: s -> Double
  6.  
  7. data Rectangle = Rectangle {
  8.  width :: Double,
  9.  height :: Double
  10. } deriving Show
  11.  
  12. instance Shape Rectangle where
  13.  area rectangle = (width rectangle) * (height rectangle)
  14.  perimeter rectangle = 2 * ((width rectangle) + (height rectangle))
  15.  
  16. data Circle = Circle {
  17.  radius :: Double
  18. } deriving Show
  19.  
  20. instance Shape Circle where
  21.  area circle = pi * (radius circle) * (radius circle)
  22.  perimeter circle = 2.0 * pi * (radius circle)
  23.  
  24. r=Rectangle 10.0 3.0
  25. c=Circle 10.0
  26. list=[WrapShape r,WrapShape c]
  27.  
  28. data ShapeWrapper where
  29.  WrapShape :: Shape s => s -> ShapeWrapper
  30.  
  31. getArea :: ShapeWrapper -> Double
  32. getArea (WrapShape s) = area s
  33.  
  34. getPerimeter :: ShapeWrapper -> Double
  35. getPerimeter (WrapShape s) = perimeter s
  36.  
  37. areas = map getArea list
  38. perimeters = map getPerimeter list
clone this paste RAW Paste Data