How overload operator in Haskell?

Hal Daume t-hald@microsoft.com
Wed, 9 Jul 2003 08:11:23 -0700


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 =3D zipWith (+) v1 v2
  (-) v1 v2 =3D zipWith (-) v1 v2
  negate v1 =3D map negate v1
  abs v1 =3D map abs v1
  (*) v1 v2 =3D ...
  fromInteger i =3D ...
  signum v1 =3D ...

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 =3D [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


> -----Original Message-----
> From: haskell-admin@haskell.org=20
> [mailto:haskell-admin@haskell.org] On Behalf Of Liu Junfeng
> Sent: Wednesday, July 09, 2003 7:25 AM
> To: haskell@haskell.org
> Subject: How overload operator in Haskell?
>=20
>=20
> I've learned haskell months, but I still can't understand the=20
> type system very well.
> I can only write:
> -----------------------------------
> type Vector =3D [Double]
> vadd,vsub :: Vector->Vector->Vector
> v1 `vadd` v2 =3D zipWith (+) v1 v2
> v1 `vsub` v2 =3D zipWith (-) v1 v2
> svmul :: Double->Vector->Vector
> s `svmul` v =3D map (s*) v
> ------------------------------------
> Tough it works, it is not convenient to use. How to create a=20
> Vector type and overload=20
> mathematical operators?=20
> Thanks for your help.=20
>=20
> Liu Junfeng
> liujf@softhome.net
>=20
>=20
>=20
> _______________________________________________
> Haskell mailing list
> Haskell@haskell.org
> http://www.haskell.org/mailman/listinfo/haskell
>=20