[Haskell-cafe] adding the elements of two lists

Richard O'Keefe ok at cs.otago.ac.nz
Mon Mar 26 01:28:54 CEST 2012


On 26/03/2012, at 1:01 AM, TP wrote:

> Hello,
> 
> My primary problem may be reduced to adding elements of two lists:
> [1,2,3] + [4,5,6] = [5,7,9]

zipWith (+) [1,2,3] [4,5,6]
gets the job done.
> 
> However, it seems it is not possible to do that:
> 
> -------------------
> instance Num [Int] where
> 	l1 + l2 = ....
> -------------------
> 
> Why?

Because the 'instance' machinery is keyed off the *outermost* type
constructor (here []) not the *whole* type (here [Int]) and the
reason for that is polymorphism; we want to be able to work with
[t] where t is not specially constrained.

You *can* do
	instance (Num t) => Num [t] where ...

> It seems it is necessary to do:
> 
> ------------------
> newtype ListOfInt = ListOfInt { getList :: [Int] }

That's *still* a good idea because there are lots of different
things that arithmetic on lists might mean.  For example,
is [1,2] + [3,4,5] an error or not?  If it is not an error,
what actually happens?




More information about the Haskell-Cafe mailing list