What is zip (functional programming?)

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

+41
functional-programming clojure zip
Jul 12 '09 at 8:28
source share
5 answers

Zip is when you take two input sequences and create an output sequence in which each two elements of the input sequences in the same position are combined using some function. Haskell example:

Input:

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

Output:

 [5, 7, 9] 

The above is a more general definition; sometimes zip refers to combining elements as tuples. For example. in Haskell again:

Input:

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

Output:

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

And a more general version is called "zip with". You can consider zip as a special case of zipWith:

 zip xs ys = zipWith (\xy -> (xs, ys)) xs ys 
+70
Jul 12 '09 at 8:31
source share

zip is a general method of functional programming, such as map or fold. You will find these functions in early methods before ruby ​​and python. They are designed to perform general batch operations in lists.

In this particular case, zip takes two lists and creates a new list of tuples from these lists.

for example, let's say you have a list with (1,2,3), and the other with ("one", "two", "three") If you fasten them together, you will get List ((1, "one") , (2, two), (3, three))

or from the scala command line, you will 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, not knowing functional programming, I thought it was related to the compression format. After I learned more about functional programming, I used it more and more.

+19
Jul 12 '09 at 8:34
source share

Unfortunatley I do not have enough points to leave a comment on the top answer, but

 zip xs ys = zipWith xs ys (\xy -> (xs, ys)) 

wrong , it should be:

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

or simply:

 zip = zipWith (\xy -> (x,y)) 
+9
Nov 25 '09 at 17:02
source share

You can use the following code in Python:

 >>> a = [1,2] >>> b = [3,4] >>> zip(a,b) [(1,3),(2,4)] 
+7
Jul 12 '09 at 8:52
source share

Paul's answer pretty much describes it. I just provided an F # example:

 let x = [1;2] let y = ["hello"; "world"] let z = Seq.zip xy 

The value z will be a sequence containing tuples of elements in one position from two sequences:

 [(1, "hello"); (2, "world")] 
+6
Jul 12 '09 at 8:38
source share



All Articles