The zip Function
Explore how to combine two lists into a list of pairs using the zip function in functional programming. Understand the generalization of zip called zipWith, which applies a binary function to paired elements of two lists. Learn to solve common problems like summing pairs, computing differences, and more, using these powerful abstractions in OCaml.
We'll cover the following...
zip two lists into a list of pairs
Functions like map, filter, and fold have a limitation—they only work with a single list. What if we want to combine multiple lists?
In the functional paradigm, there is another powerful function abstraction called zip. One form of zip takes two input lists and returns a list of corresponding pairs. We can implement such a zip function in OCaml, as shown below:
Note: If we apply the
zipfunction to two lists of different lengths, it simply ignores the additional elements of the longer list.
Let’s apply the zip function to form a list of points in the 2D plane. Assume we have two lists, ...