[Haskell-cafe] adding the elements of two lists
cdsmith at gmail.com
Mon Mar 26 01:51:14 CEST 2012
"Jonathan Grochowski" <jongrocho+hs at gmail.com> wrote:
> As Michael suggests using zipWith (+) is the simplest solution.
> If you really want to be able to write [1,2,3] + [4,5,6], you can define
the instnace as
> instance (Num a) => Num [a] where
> xs + ys = zipWith (+) xs ys
You can do this in the sense that it's legal Haskell... but it is a bad
idea to make lists an instance of Num, because there are situations where
the result doesn't act as you would like (if you've had abstract algebra,
the problem is that it isn't a ring).
More concretely, it's not hard to see that the additive identity is
[0,0,0...], the infinite list of zeros. But if you have a finite list x,
then x - x is NOT equal to that additive identity! Instead, you'd only get
a finite list of zeros, and if you try to do math with that later, you're
going to accidentally truncate some answers now and then and wonder what
In general, most type classes in Haskell are like this... the compiler only
cares that you provide operations with certain types, but the type class
also carries around additional "laws" that you should obey when writing
instances. Here there's no good way to write an instance that obeys the
laws, so it's better to write no instance at all.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Haskell-Cafe