[Haskell-cafe] adding the elements of two lists

Jonathan Grochowski jongrocho+hs at gmail.com
Sun Mar 25 14:37:07 CEST 2012


On Sun, Mar 25, 2012 at 5:01 AM, TP <paratribulations at free.fr> wrote:

> Hello,
>
> My primary problem may be reduced to adding elements of two lists:
> [1,2,3] + [4,5,6] = [5,7,9]
>
> My first idea was to declare a list of Int as an instance of Num, and
> define (+)
> in the correct way.
> However, it seems it is not possible to do that:
>
> -------------------
> instance Num [Int] where
>        l1 + l2 = ....
> -------------------
>
> Why?
> It seems it is necessary to do:
>
> ------------------
> newtype ListOfInt = ListOfInt { getList :: [Int] }
>    deriving (Show, Eq)
>
> instance Num ListOfInt where
>     l1 + l2 = ...
> -------------------
>
> Am I correct? Is it the best way to do that?
>
> Now, what is the most usual way to implement l1+l2?
> I have just read about applicative functors, with which I can do:
>
> -------------------
> import Control.Applicative
> let l1 = [1,2,3]
> let l2 = [4,5,6]
> print $ getZipList $ (+) <$> ZipList l1 <*> ZipList l2
> [5,7,9]
> -------------------
>
> Is it the correct way to do that?
> I have tried:
>
> -------------------
> instance Num ListOfInt where
>     l1 + l2 = ListOfInt $ getZipList $ (+) <$> ZipList (getList l1) <*>
>                                     ZipList (getList l2)
> -------------------
>
> Isn't it too much complicated?
>
> Thanks
>
> TP
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>

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'll also likely want to give definitions for the other functions ((*),
abs, signum, etc.) as well.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20120325/6a62e65e/attachment.htm>


More information about the Haskell-Cafe mailing list