How to add two lists in haskell?

11,678

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 xes and one inside it over the ys. 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.

Share:
11,678
Alex
Author by

Alex

Updated on June 24, 2022

Comments

  • Alex
    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
    kosmikus about 10 years
    There's also a language extension called ParallelListComp (parallel list comprehensions) that allows you to write func1 almost as given in the question: func1 x y = [ a + b | a <- x | b <- y ]
  • Ry-
    Ry- about 10 years
    So the same thing as what was already said 5 hours earlier?
  • Will Ness
    Will Ness about 10 years
    this shows that zipWith is just a kind of map itself.
  • Kye Frn
    Kye Frn about 10 years
    I thought it appropriate to give an answer numerically exact to the stated question.
  • Tarmil
    Tarmil about 10 years
    @WillNess In fact ML languages tend to call it map2.
  • Daniel Bammer
    Daniel Bammer almost 3 years
    if 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