[Haskell-cafe] OOP'er with (hopefully) trivial questions.....
Nicholls, Mark
Nicholls.Mark at mtvne.com
Mon Dec 17 06:14:51 EST 2007
OK I'll have to digest this and mess about a bit....but can I make an
observation at this point....
If I define "Shape" like
data Shape = Circle Int
| Rectangle Int Int
| Square Int
Isn't this now "closed"...i.e. the statement is effectively defining
that shape is this and only ever this....i.e. can I in another module
add new "types" of Shape? (sorry about all the quotation marks, but it's
a minefield of potential confusions over types, classes etc).
My other observation is...are the things on the right hand side of the
the "="'s sign not types?
The lower version makes more sense to me...I'll have to give it a go....
A P.S. would be...I tend to write code rather than mess about in the
GHCi shell.....is there a way in code to output the type of a
value..i.e. the ":t" operation?
-----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