What is zip (functional programming?)
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 ?
Solution 1:
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
Solution 2:
zip is a common functional programming method like map or fold. You will find these functions in early lisps all the way up to ruby and python. They are designed to perform common batch operations on lists.
In this particular case, zip takes two lists and creates a new list of tuples from those lists.
for example, lets say you had a list with (1,2,3) and another with ("one","two","three") If you zip them together, you will get List((1,"one"), (2,"two"), (3,"three"))
or from the scala command line, you would get:
scala> List(1,2,3).zip(List("one","two","three"))
res2: List[(Int, java.lang.String)] = List((1,one), (2,two), (3,three))
When I first saw it in Python, without knowing functional programming, I thought it was related to the compression format. After I learned more about functional programming, I've used it more and more.