liveBook · Manning

Zip

As explained in Learn Haskell by Example

zip is a standard Haskell function that combines two lists element-wise into a list of pairs, stopping when the shorter list ends.

zip combines two lists element by element, producing pairs with type [a] -> [b] -> [(a, b)]. It stops when the shorter list ends. section 4.3.3

This makes zip useful for pairing line numbers with lines and for constructing associative lists without writing specialized recursive code. unzip separates pairs again, but it cannot restore elements discarded from a longer input list. section 4.3.3

Pairing positions with values

zip [1,2,3] ["Hello", "World", "!"] produces [(1,"Hello"),(2,"World"),(3,"!")]. With zip [1..10] [], the result is [], because the empty list determines the stopping point.

When each pair should be transformed immediately, use zipWith, whose type is (a -> b -> c) -> [a] -> [b] -> [c].

How Learn Haskell by Example covers it

How deep it goes
Explains the polymorphic type, element-wise behavior, shortest-list rule, unzip limitation, and zipWith relationship.
Examples
Demonstrates pairing numbers with strings or characters and truncating results when one input list is shorter.
What you can do after
Apply zip and zipWith to combine lists element-wise and recognize truncation caused by unequal lengths.
How it connects
Connects zip with lists, tuples, associative lists, unzip, zipWith, and line numbering.

Also explained in

Compare how 5 books explain zip →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.