[Haskell-cafe] adding the elements of two lists

David Fox ddssff at gmail.com
Thu Mar 29 08:18:50 CEST 2012


On Sun, Mar 25, 2012 at 5:06 AM, Michael Snoyman <michael at snoyman.com> wrote:
> On Sun, Mar 25, 2012 at 2:01 PM, 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
>
> A simple solution is to use the zipWith[1] function:
>
>    zipWith (+) [1,2,3] [4,5,6] == [5,7,9]
>
> It takes a bit of time to get acquainted with all of the incredibly
> convenient functions in base, but once you know them, it can greatly
> simplify your code.
>
> Michael

Not knowing zipWith, I usually write

   map (uncurry (+)) (zip [1,2,3] [4,5,6])



More information about the Haskell-Cafe mailing list