How overload operator in Haskell?

Jerzy Karczmarczuk karczma@info.unicaen.fr
Wed, 09 Jul 2003 17:25:20 +0200


Hal Daume answers a question on how to define nice, infix ops
acting on vectors:

> What you want to do is make your Vector an instance of the Num(eric)
> type class.  For instance:
> 
> instance Num Vector where
>   (+) v1 v2 = zipWith (+) v1 v2
>   (-) v1 v2 = zipWith (-) v1 v2
>   negate v1 = map negate v1
>   abs v1 = map abs v1
>   (*) v1 v2 = ...
>   fromInteger i = ...
>   signum v1 = ...
> 
> I've left the last three blank because it's unclear what should go
> there.  Since (*) has type Vector->Vector->Vector (in this instance),
> you can't use dot product or something like that.
> 
> signum :: Vector->Vector could be written and just return [-1], [0] or
> [1], I suppose.
> 
> fromInteger :: Integer->Vector is a little harder.  Perhaps just
> 'fromInteger i = [fromInteger i]' would be acceptable.  Or you could
> leave these undefined.
> 
>  --
>  Hal Daume III                                   | hdaume@isi.edu
>  "Arrest this man, he talks in maths."           | www.isi.edu/~hdaume

While this is a possible solution, I would shout loudly: "Arrest this man, he
is disrespectful wrt math!". Actually, this shows once more that the Num class
and its relatives is a horror...

Signum in this context has no sense. The multiplication might be the cross
product, but its anti-commutativity shows plainly that this is not a 'standard'
multiplication. 'fromInteger' has even less sense than signum...
I am particularly horrified by "abs v = map abs v", and I am sure all of you
see why.


I think that a more sane solution would be the definition of a particular class
with operations porting names like <+>, or ^+^, or whatever similar to standard
ones, but different.

Jerzy Karczmarczuk