[Haskell-beginners] Re: Type classes are not like interfaces, after all

Ertugrul Soeylemez es at ertes.de
Fri Jan 23 09:08:58 EST 2009


Francesco Bochicchio <bieffe62 at gmail.com> wrote:

> I think I get the polymorphism. What I don't get is why a specialized
> type cannot replace a more generic type, since the specialized type
> implements the interface defined in the generic type.

Don't confuse this kind of polymorphism with the one you usually find in
OOP languages.  Consider your original function again.  Let me change
its name to make it clearer:

  arbitraryNum :: Num n => n
  arbitraryNum = 3 :: Integer

If 'arbitraryNum' is referenced somewhere else, then the result is
expected to be of type 'Num n => n'.  It may be referenced as an
Integer, as a Float, as a complex number, etc., whatever is a Num
instance is valid here.  So the value you're trying to give
'arbitraryNum' is of a too specific type.  You're trying to use
information, which you don't have, namely that 'n' is an Integer.  The
only information about 'n' you have is that it's a Num type.

Now the Num type class contains the fromInteger function, which you can
use to convert any Integer to a Num type.  So you can write:

  arbitraryNum :: Num n => n
  arbitraryNum = fromInteger (3 :: Integer)

You take 3, which is an Integer, and use fromInteger to convert it to
'Num n => n'.  Try to think for a moment about what the outcome of the
following function can be:

  arbitraryValue :: a
  arbitraryValue = ...?

You should come to the conclusion that arbitraryValue cannot return
anything, because it doesn't have any information about what it's
supposed to return.  What is the type 'a'?  What information do you have
about 'a'?  No information.  Not even enough information to construct a
value of type 'a'.  The type 'a' is most polymorphic and its value is
least defined.

Of course, you can write such a function, under the strict requirement
that it never returns a value.  You say, the result of such a function
is 'bottom'.  For example:

  bottom :: a
  bottom = bottom

This function never returns.  It recurses forever.


Greets,
Ertugrul.


-- 
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://blog.ertes.de/




More information about the Beginners mailing list