Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add two lists in haskell? [duplicate]

Tags:

haskell

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?

like image 569
Alex Avatar asked Oct 16 '13 14:10

Alex


2 Answers

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.

like image 62
J. Abrahamson Avatar answered Sep 21 '22 20:09

J. Abrahamson


The simple answer is zipWith:

zipWith (+) [1,2,3][5,4,6]
like image 29
Kye Frn Avatar answered Sep 23 '22 20:09

Kye Frn