How to add two lists in haskell?
Solution 1
You're looking for zipWith
. In particular func1 x y = zipWith (+) x y
. You can "eta reduce" to remove those extra parameters as well: func1 = zipWith (+)
. This is the most efficient form I can think of.
Your current method doesn't work because [a+b | a <- x, b <- y]
forms two nested loops, one over the x
es and one inside it over the y
s. This is the nature of list comprehensions and it's based on Set Builder Notation. One way to read it is "for each a from x, for each b from y, give me (a + b)
" while we actually want to run through x
and y
together.
Solution 2
The simple answer is zipWith:
zipWith (+) [1,2,3][5,4,6]
Solution 3
sum' :: [Int] -> [Int] -> [Int]
sum' xs ys = map (uncurry (+)) $ zip xs ys
You can combine the above map
and zip
into a single function zipWith
as zipWith f xs ys = map (uncurry f) $ zip xs ys
.
Alex
Updated on June 24, 2022Comments
-
Alex over 1 year
how can I add for example [1,2,3] to [5,4,6] to return [6,6,8] This is what I have so far:
func1 :: [Int]->[Int]->[Int] func1 x y = [a+b|a<-x,b<-y]
Should I try and remove the elements that I don't want or is there a simpler way to do this?
-
kosmikus about 10 yearsThere's also a language extension called
ParallelListComp
(parallel list comprehensions) that allows you to writefunc1
almost as given in the question:func1 x y = [ a + b | a <- x | b <- y ]
-
Ry- about 10 yearsSo the same thing as what was already said 5 hours earlier?
-
Will Ness about 10 yearsthis shows that
zipWith
is just a kind ofmap
itself. -
Kye Frn about 10 yearsI thought it appropriate to give an answer numerically exact to the stated question.
-
Tarmil about 10 years@WillNess In fact ML languages tend to call it
map2
. -
Daniel Bammer almost 3 yearsif the lists are not of the same length zipWith discards the rest. Try this:
zipSum (a : as) (b : bs) = a + b : zipSum as bs
zipSum as [] = as
zipSum [] bs = bs