<div class="gmail_quote">On Sun, Mar 25, 2012 at 5:01 AM, TP <span dir="ltr">&lt;<a href="mailto:paratribulations@free.fr" target="_blank">paratribulations@free.fr</a>&gt;</span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">

Hello,<br>
<br>
My primary problem may be reduced to adding elements of two lists:<br>
[1,2,3] + [4,5,6] = [5,7,9]<br>
<br>
My first idea was to declare a list of Int as an instance of Num, and define (+)<br>
in the correct way.<br>
However, it seems it is not possible to do that:<br>
<br>
-------------------<br>
instance Num [Int] where<br>
        l1 + l2 = ....<br>
-------------------<br>
<br>
Why?<br>
It seems it is necessary to do:<br>
<br>
------------------<br>
newtype ListOfInt = ListOfInt { getList :: [Int] }<br>
    deriving (Show, Eq)<br>
<br>
instance Num ListOfInt where<br>
     l1 + l2 = ...<br>
-------------------<br>
<br>
Am I correct? Is it the best way to do that?<br>
<br>
Now, what is the most usual way to implement l1+l2?<br>
I have just read about applicative functors, with which I can do:<br>
<br>
-------------------<br>
import Control.Applicative<br>
let l1 = [1,2,3]<br>
let l2 = [4,5,6]<br>
print $ getZipList $ (+) &lt;$&gt; ZipList l1 &lt;*&gt; ZipList l2<br>
[5,7,9]<br>
-------------------<br>
<br>
Is it the correct way to do that?<br>
I have tried:<br>
<br>
-------------------<br>
instance Num ListOfInt where<br>
     l1 + l2 = ListOfInt $ getZipList $ (+) &lt;$&gt; ZipList (getList l1) &lt;*&gt;<br>
                                     ZipList (getList l2)<br>
-------------------<br>
<br>
Isn&#39;t it too much complicated?<br>
<br>
Thanks<br>
<br>
TP<br>
<br>
_______________________________________________<br>
Haskell-Cafe mailing list<br>
<a href="mailto:Haskell-Cafe@haskell.org" target="_blank">Haskell-Cafe@haskell.org</a><br>
<a href="http://www.haskell.org/mailman/listinfo/haskell-cafe" target="_blank">http://www.haskell.org/mailman/listinfo/haskell-cafe</a><br>
</blockquote></div><br>As Michael suggests using zipWith (+) is the simplest solution.<br><br>If you really want to be able to write [1,2,3] + [4,5,6], you can define the instnace as<br><br>    instance (Num a) =&gt; Num [a] where<br>

        xs + ys = zipWith (+) xs ys<br>
<br>You&#39;ll also likely want to give definitions for the other functions ((*), abs, signum, etc.) as well.<br>