The zip Function
Learn how the zip function can be used to combine multiple lists into a single one.
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:
Press + to interact
(** [print_int_pair_list] prints an integer pair list [l] to the console. *)let print_int_pair_list l = print_string ("[" ^ (String.concat "; " (List.map (fun p -> "(" ^ string_of_int (fst p) ^ ", " ^ string_of_int (snd p) ^ ")") l)) ^ "]")(** [zip l1 l2] zips two lists [l1] and [l2] into a single list of pairs. *)let rec zip l1 l2 = match l1, l2 with| [], _ -> []| _, [] -> []| x :: xs, y :: ys -> (x, y) :: zip xs ys(** Printing the result of 'zip [1; 2; 3] [4; 5; 6]' to the console *)let _ = print_int_pair_list (zip [1; 2; 3] [4; 5; 6])
Note: If we apply the
zip
function 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 ...