I am working on the problem for writing Haskell code similar to a C++ program.
The C++ code is:
class Rectangle
{
private:
int length;
int width;
public:
Rectangle()
{
length = 0;
width = 0;
}
Rectangle(int x)
{
length = x;
width =0;
}
Rectangle ( int x , int y)
{
length = x;
width = y;
}
};
To write similar Haskell code i made a data type Rectangle
data Rectangle = Rectangle Length Width deriving (Eq, Show , Read)
type Length = Int
type Width = Int
Then i thought of making a load function which can act as constructor. But i don’t understand how to implement function overloading with different number of arguments.
Please help. Thanks.
While it is possible to do such overloading in Haskell, it’s not considered idiomatic, and will likely lead to confusing errors later on. Instead, you should simply define functions that construct data:
This allows you to give clear names that describe the semantics of each overloading, rather than relying on the number and type of arguments given to disambiguate which you mean.
However, if you do want to write the overloaded version, you can do it easily with typeclasses:
You’ll need
{-# LANGUAGE FlexibleInstances #-}at the top of your file to compile this. A trick like this is used by the standardText.Printflibrary, but I would not consider it a particularly good example of overloading in Haskell; there is almost always some structure to the overloaded value’s type, whereas here its entire structure is dictated by the instance, which can get in the way of type inference; not only that, but there aren’t any reasonable laws that govern instances (indeed, the type is too general to permit any).But if you really want to do it, you can, and while it’s usually a bad idea, sometimes (as in the case of
printf) it’s the only way to accomplish the interface you want.To try this out in GHCi, you’ll need to specify the types you’re using explicitly, or it won’t be able to resolve the instances: