Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement function overloading in Haskell

Tags:

haskell

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.

like image 352
Rog Matthews Avatar asked Jan 25 '12 06:01

Rog Matthews


People also ask

Is there function overloading in Haskell?

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 are type classes in Haskell?

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.


1 Answers

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}
like image 129
ДМИТРИЙ МАЛИКОВ Avatar answered Jan 03 '23 22:01

ДМИТРИЙ МАЛИКОВ