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

Ketil Malde ketil+haskell at ii.uib.no
Mon Dec 17 12:12:02 EST 2007

Thomas Davie <tom.davie at gmail.com> writes:

> 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

> 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

There's a third way, too, and I haven't seen anybody mention it yet
(apologies if I just missed it).  You can provide an explicit record
of the relevant "member functions", and "instantiate" it in different
ways.  E.g.

   data Shape = Shape { area :: Int }

   square x      = Shape (x^2)
   rectangle x y = Shape (x*y)
   circle r      = Shape (pi*r^2)

If I haven't seen further, it is by standing in the footprints of giants

More information about the Haskell-Cafe mailing list