[Haskell-cafe] adding the elements of two lists

Chris Smith 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
went wrong.

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.

Chris Smith
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20120325/87f3a947/attachment.htm>

More information about the Haskell-Cafe mailing list