[Haskell-cafe] OOP'er with (hopefully) trivial questions.....

Thomas Davie tom.davie at gmail.com
Mon Dec 17 06:03:40 EST 2007

On 17 Dec 2007, at 10:46, Nicholls, Mark wrote:
> I can obviously at a later date add a new class Triangle, and not  
> have to touch any of the above code….

Yes, and you can indeed do a similar thing in Haskell.  The natural  
thing to do here would be to define a type Shape...

data Shape = Circle Int
             | Rectangle Int Int
             | Square Int

area :: Shape -> Int -- Note, this is an interesting type if you want  
the area of circles
area (Circle r) = pi * r^2
area (Rectangle h w) = h * w
area (Square l) = area (Rectangle l l)

If however, you *really* want to keep your shapes as being seperate  
types, then you'll want to invoke the class system (note, not the same  
as OO classes).

class Shape a where
   area :: a -> Int

newtype Circle = C Int

instance Shape Circle where
   area (C r) = pi * r^2

newtype Rectangle = R Int Int

instance Shape Rectangle where
   area (R h w) = h * w

newtype Square = Sq Int

instance Shape Square where
   area (Sq l) = l * l

-- Now we can do something with our shapes
doubleArea :: Shape a => a -> Int
doubleArea s = (area s) * 2

Hope that helps


More information about the Haskell-Cafe mailing list