
On 17 Dec 2007, at 11:14, Nicholls, Mark wrote:
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).
That's correct, another module could not add constructors to this type. The idea here is that you tell it all of the possible ways to construct Shape, and can then write functions to deal with it elsewhere.
My other observation is...are the things on the right hand side of the the "="'s sign not types? Correct, they're constructors. So you could never for example write a function that accepts only Rectangles (unless you start getting into odd type extensions)
The lower version makes more sense to me...I'll have to give it a go....
Both versions make sense. They differ only in how "heavy weight" they are. Defining a type allows you to do pattern matching on the constructors, and is a much better way of defining anything you know the structure of in the first place. Using the class system on the other hand, gives you more flexibility, but at the cost of a lot of readability. The class system is designed to be able to describe things that aren't explicitly the same type, but exhibit similar properties. For example the Eq class describes all things that are equatable, it defines the (==) and (/=) operators. Your Shape class describes all types in which it's sane to compute an area.
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?
Take a look at the Typable class. Although, pretty much any code that you can compile can be loaded into ghci without modification, and that's by far the easier way of finding the types of things. Bob