
Haskell supports parametric polymorphism in the sense as, for example,
operations on lists. Thus function List.length::[a]->Int is
polymorphic.
The difference between polymorphism and overloading is that
polymorphism basically means that there is one algorithm for different
types of operands whereas overloading means that for one symbol there
are different implementations.
Haskell compiler converts an overloaded function in such way that the
function is passed an additional argument -- a dictionary that
contains implementation of operations defined in the class.
Consider function square:
square :: Num n => n -> n
square x = x*x
class Num a where
(+) :: a -> a -> a
(-) :: a -> a -> a
negate :: a->a
...etc...
instance Num Int where
(+) = intPlus a b
(*) = intMult a b
negate a = intNeg a
...etc...
where functions intPlus, intMult, intNeg are defined somewhere else.
So at compile time the type of square :: Num n => n -> n is replaced with
square :: numDict n -> n -> n
where numDict a is a parametric data type with defined accessor
functions that return implementation of operations defined in the
class.
On 16 December 2010 19:34, Dennis Raddle
I looked up the difference between polymorphism and overloading (speaking of all languages in general), and apparently polymorphism is a general term for an operation that can accept arguments of different types. Overloading is a form of "ad-hoc polymorphism" in which the compiler chooses specific code to be executed by inspecting the arguments at compile time. Apparently "true polymorphism" means exactly the same code is executed no matter what the argument types, such as implemented by inheritance in C++ (*) Now my understanding of Haskell's classes is that the compiler chooses the right instance of the class at compile time. Does that mean that Haskell implements only ad-hoc polymorphism?
(*) Another question: if someone says "What feature of C++ makes polymorphism possible?" What is the correct answer? Inheritance? Virtual methods? Some combination?
-D
_______________________________________________ Beginners mailing list Beginners@haskell.org http://www.haskell.org/mailman/listinfo/beginners
-- Best, Eugene Perederey -- Best, Eugene Perederey
participants (1)
-
Eugene Perederey