[Haskell-beginners] Type classes and synonyms

Stephen Tetley stephen.tetley at gmail.com
Sat Nov 21 11:34:33 EST 2009


Hello Philip

If you are wanting element-wise addition with two lists, you can do

> instance Num a => Num [a] where
>   (+) = zipWith (+)
>   (-) = zipWith (-)
>   (*) = zipWith (*)
>   fromInteger = repeat . fromInteger
>   abs         = map abs
>   signum      = map signum


Plus as you are representing timestamped values as pairs you would
need a Num instance for pairs...

> instance (Num a,Num b) => Num (a,b) where
>   (+) (a,b) (x,y) = (a+x,b+y)
>   (-) (a,b) (x,y) = (a-x,b-y)
>   (*) (a,b) (x,y) = (a*x,b*y)
>   fromInteger a = (fromInteger a, fromInteger a)
>   abs (a,b)        = (abs a, abs b)
>   signum (a,b)     = (signum a, signum b)

But... these instances are somewhat arbitrary, and other people
would no doubt disagree with their details:

For Num on lists there is the problem of uneven length lists.
Also fromInteger has a valid definintion as

fromInteger a = a : repeat 0

Hence, there aren't instances in the Hierarchical Libraries.

Uneven lists can be solved with Streams - see Ralf Hinze's
Streams, but then you move to infinite lists... Oh well.

http://hackage.haskell.org/packages/archive/hinze-streams/1.0/doc/html/Data-Stream-Hinze-Stream.html

As for your question, you can't use a type synonym to define
different class instances, you have to use a newtype. Perhaps the
best illustration is in Data.Monoid - Numbers have several useful
monoids, two of them are:

addition (0,+)
multiplication (1,*)

Data.Monoid uses the Sum newtype wrapper to define the addition
monoid and the Product newtype wrapper to define the
multiplication monoid.


Best wishes

Stephen


More information about the Beginners mailing list