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.
However, it is possible for a language to have overloading and not to have automatic conversion. Haskell, for example, does not do automatic conversion. Parametric polymorphism can be contrasted with overloading.
What's a typeclass in Haskell? A typeclass defines a set of methods that is shared across multiple types. For a type to belong to a typeclass, it needs to implement the methods of that typeclass. These implementations are ad-hoc: methods can have different implementations for different types.
You can use record syntax to reach that behavior.
data Rectangle = Rectangle {len :: Length, width :: Width} deriving (Eq, Show , Read)
type Length = Int
type Width = Int
rectangle = Rectangle { len = 0, width = 0 }
rectangle :: Rectangle will be your constructor here.
Now you can define some Rectangle values:
λ> let a = rectangle {len = 1}
λ> a
Rectangle {len = 1, width = 0}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With