What is zip (functional programming?)

Robert Gould picture Robert Gould · Jul 12, 2009 · Viewed 25.5k times · Source

I recently saw some Clojure or Scala (sorry I'm not familiar with them) and they did zip on a list or something like that. What is zip and where did it come from ?

Answer

Pavel Minaev picture Pavel Minaev · Jul 12, 2009

Zip is when you take two input sequences, and produce an output sequence in which every two elements from input sequences at the same position are combined using some function. An example in Haskell:

Input:

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

Output:

[5, 7, 9]

The above is a more generic definition; sometimes, zip specifically refers to combining elements as tuples. E.g. in Haskell again:

Input:

zip [1, 2, 3] [4, 5, 6]

Output:

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

And the more generic version is called "zip with". You may consider "zip" as a special case of "zipWith":

zip xs ys = zipWith (\x y -> (xs, ys)) xs ys