Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell does not support the C++ overloading style in which functions with different types share a common name

Tags:

haskell

I am learning Haskell. When I gone through following documentation. https://www.haskell.org/tutorial/classes.html

It is mentioned that "Haskell does not support the C++ overloading style in which functions with different types share a common name." I am not getting this statement, I guess ad-hoc polymorphism (which is done by using type classes) is equivalent to method overloading in C++, Java. Can some body explain me is my understanding correct ?

class Equal a where

    isEquals :: a -> a -> Bool


type Id = Int
type Name = String

data Employee = Engineer Id Name 

data Student = Student Id Name

getEmpId (Engineer empId _) = empId
getStudId (Student studId _) = studId

instance Equal Employee where
    isEquals emp1 emp2 = getEmpId emp1 == getEmpId emp2

instance Equal Student where
    isEquals stud1 stud2 = getStudId stud1 == getStudId stud2

In the above snippet 'isEquals' function is applied to two different types Employee, Student which is equivalant of overloading in C++, Java. Is my understanding correct?

like image 611
Hari Krishna Avatar asked Dec 20 '25 23:12

Hari Krishna


1 Answers

Partially, yes. However, keep in mind that signature of your isEquals is always a -> a. In C++ you could easily write:

int foo(int a, int b)
int foo(int a, char b)
int foo(char a, char b)

By using typeclasses you're only able to get first and third function, never the second.

UPDATE 1:

as noted in comments, you can achieve the second version by using MultiParamTypeClasses extension (if you're using GHC). Still, there is fourth version:

int foo(int a, int a, int a)

which has wrong arity if you use a typeclass, but is perfectly fine in C++.

like image 197
Tomasz Lewowski Avatar answered Dec 23 '25 14:12

Tomasz Lewowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!