[Haskell-cafe] adding the elements of two lists
TP
paratribulations at free.fr
Sun Mar 25 14:01:35 CEST 2012
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
More information about the Haskell-Cafe
mailing list