Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zipWith function in Haskell

Tags:

haskell

ghci> zipWith' (zipWith' (*)) [[1,2,3],[3,5,6],[2,3,4]] [[3,2,2],[3,4,5],[5,4,3]]

The function zipWith' use function '*' and parameters after it to get the return.But in this case,how the function zipWith' to get the result [[3,4,6],[9,20,30],[10,12,12]] .

The code example using zipWith' was taken verbatim from the free online book Learn You a Haskell for Great Good.

like image 429
CathyLu Avatar asked Jan 20 '11 04:01

CathyLu


1 Answers

zipWith calls the given function pairwise on each member of both lists. So zipWith f [a,b,c] [x,y,z] evaluates to [f a x, f b y, f c z]. In this case f is zipWith (*) and the elements of the lists are again lists, so you get:

[ zipWith (*) [1,2,3] [3,2,2],
  zipWith (*) [3,5,6] [3,4,5], 
  zipWith (*) [2,3,4] [5,4,3] ]

Now the inner calls to zipWith multiply the elements of the inner lists pairwise, so you get:

[ [3,4,6],
  [9,20,30],
  [10,12,12] ]
like image 55
sepp2k Avatar answered Sep 20 '22 15:09

sepp2k