[Haskell-cafe] adding the elements of two lists

Richard O'Keefe ok at cs.otago.ac.nz
Mon Mar 26 04:55:17 CEST 2012


On 26/03/2012, at 12:51 PM, Chris Smith wrote:
> 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!

Said another way:  if you do want [num] to support + and -, then you DON'T
want the definitions of + and - to be unthinking applications of zipWith.

The approach I took the time I did this (before I learned better) was this:

	smart_cons :: Num t => t -> [t] -> [t]
	smart_cons 0 [] = []
	smart_cons x xs = x : xs

	instance Num t => Num [t]
	  where  (x:xs) + (y:ys) = smart_cons (x+y) (xs + ys)
	         xs     + []     = xs
		 []     + ys     = ys
		 ...
		fromInteger 0 = []
		fromInteger n = [n]
		...

so that a finite list acted _as if_ it was followed by infinitely many zeros.
Of course this wasn't right either: if the inputs don't have trailing zeroes,
neither do the outputs, but if they _do_ have trailing zeros, [0]+[] => [0]
when it should => [].  That was about the time I realised this was a bad idea.





More information about the Haskell-Cafe mailing list