[Haskell-cafe] Constraints at construction
Iain Barnett
iainspeed at gmail.com
Thu Oct 9 09:02:44 EDT 2008
If I were to create an object in C#, for instance, I could add code
to the constructor that might limit the type further e.g.
public class Car
{
string model;
int wheels;
public Car ( string model, int no_of_wheels )
{
if ( no_of_wheels <= 2 ) {
throw new Exception( "a car must have at least 3 wheels");
}
this.model = model;
this.no_of_wheels = no_of_wheels;
}
}
or I could specify all sorts of things, like the size of an array
could only be a certain length, or whatever. Similarly, when creating
a column with SQL I'd be able to specify further constraints on the
column than just it's type.
I don't see how to do this with Haskell and the data keyword. Is
there a tutorial someone could point me to, or an explanation of
this? Or is it that I have to wrap the creation in an accessor
function that checks the inputs first?
type Model = String
type Wheels = Int
data Car = Car Model Wheels
car_maker model wheels = if wheels <= 2 then error ...
else Car model wheels
?
Most of my programming career (if you can call it that:) has been
primarily with C# and SQL, and perhaps this heady mixture of OOP and
hacked-functional is confusing me!
Iain
More information about the Haskell-Cafe
mailing list