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

Nicholls, Mark Nicholls.Mark at mtvne.com
Mon Dec 17 06:47:02 EST 2007

```Ooo

"The constructor of a newtype must have exactly one field   but `R' has
two In the newtype declaration for `Rectangle'"

It doesn't like

"newtype Rectangle = R Int Int"

-----Original Message-----
From: Thomas Davie [mailto:tom.davie at gmail.com]
Sent: 17 December 2007 11:04
To: Nicholls, Mark
Cc: haskell-cafe at haskell.org
Subject: Re: [Haskell-cafe] OOP'er with (hopefully) trivial
questions.....

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

Bob
```

More information about the Haskell-Cafe mailing list