[Haskell-cafe] type gurus, can you please help?
Bulat Ziganshin
bulat.ziganshin at gmail.com
Mon Aug 14 02:37:37 EDT 2006
Hello haskell,
i'm started to write article about type classes. can you, type gurus,
please check this initial text for correctness in explaining
differences between classes and type classes?
at this moment C++/C#/Java languages has classes and
templates/generics. what is a difference? with a class, type
information carried with object itself while with templates it's
outside of object and is part of the whole operation
for example, if == operation is defined in a class, the actual
procedure called for a==b may depend on run-time type of 'a' but if it
is defined in template, actual procedure depends only on template
instantiated (and determined at compile time)
Haskell's objects don't carry run-time type information. instead,
class constraint for polymorphic operation passed in form of
"dictionary" implementing all operations of the class (there are also
other implementation techniques, but this don't matter). For example,
eqList :: (Eq a) => [a] -> [a] -> Bool
translated into:
type eqDictionary a = (a->a->Bool, a->a->Bool)
eqList :: eqDictionary a -> [a] -> [a] -> Bool
where first parameter is "dictionary" containing implementation of
"==" and "/=" operations for objects of type 'a'. If there are several
class constraints, dictionary for each is passed.
If class has base class(es), the dictionary tuple also includes tuples
of base classes dictionaries:
class Eq a => Cmp a where
cmp :: a -> a -> Comparision
cmpList :: (Cmp a) => [a] -> [a] -> Comparision
turns into:
type cmpDictionary a = (eqDictionary a, a -> a -> Comparision)
cmpList :: cmpDictionary a -> [a] -> [a] -> Bool
Comparing to C++, this is like the templates, not classes! As with
templates, typing information is part of operation, not object! But
while C++ templates are really form of macro-processing (like
Template Haskell) and at last end generates non-polymorphic code,
Haskell's using of dictionaries allows run-time polymorphism
(explanation of run-time polymorphism?).
Moreover, Haskell type classes supports inheritance. Run-time
polymorphism together with inheritance are often seen as OOP
distinctive points, so during long time i considered type classes as a
form of OOP implementation. but that's wrong! Haskell type classes
build on different basis, so they are like C++ templates with added
inheritance and run-time polymorphism! And this means that usage of
type classes is different from using classes, with its own strong and
weak points.
--
Best regards,
Bulat mailto:Bulat.Ziganshin at gmail.com
More information about the Haskell-Cafe
mailing list