[Haskell-cafe] Confused about types

Cale Gibbard cgibbard at gmail.com
Sat Oct 1 02:30:22 EDT 2005


Note that you can't pattern match to make special cases for handling
particular types, only against data constructors in the specific type
which your function accepts as input.

You need a typeclass if you want to have a function which acts
differently at different types. As you might have realised abs is
somewhat ineffective for comparing the magnitudes of numbers which
aren't already in Ord, as it will produce a value of the same type.

The main trouble here is that
  abs :: (Num a) => a -> a
and doesn't help to order the complex numbers. On the other hand, there is
  magnitude :: (RealFloat a) => Complex a -> a
which will take your Complex Double and give you back a Double, for
instance, and Double will be ordered, which is exactly what you want.

The quickest way to solve this problem is to just make a typeclass for
the Newton's method functions, and put them in it, and change the
implementation for the Complex instance. You might also consider
making a class for a general norm operation, but this would pretty
much necessarily be a multiparameter typeclass, and you'd likely want
to use functional dependencies, so that the result type would be
determined by the input type.

hope this helps,
 - Cale


More information about the Haskell-Cafe mailing list