One problem five solutions — Zip Function

zip [1, 2, 3] [4, 5, 6]
-- outputs [(1,4),(2,5),(3,6)]
zip [1, 2, 3] [4, 5]
-- outputs [(1,4),(2,5)]
zip [1, 2] [4, 5, 6]
-- outputs [(1,4),(2,5)]

Haskell

As I mentioned Haskell has a zip function, but I believe that it will be very didactic for this article if we start by implementing a zip function from scratch in Haskell, just for learning purposes

myzip [] _ = []
myzip _ [] = []
myzip (x:xs) (y:ys) = (x, y):myzip xs ys
  • if the first list is empty we can’t pair it in a tuple, so we return an empty list
  • if the second list is empty, we still can't have a pair in a tuple and return the empty list
  • if both lists still have elements we get the first element x of the first list and the first element y of the second list, add them to a tuple and append them to the array with the ‘:’ symbol and call recursively the ‘myzip’ function with the rest of both lists

Elixir

Keep going with the functional languages, the second solution, will be the Elixir one:

defmodule Zip do
def zip(_, []), do: []
def zip([], _), do: []
def zip([x | xs], [y | ys]), do: [{x, y} | zip(xs, ys)]
end

JavaScript

Now it's the turn of the building block of the web, let's have a look at the zip JavaScript function:

const zip = (ls1, ls2) => {
const zips = []
for (let i = 0; i < ls1.length; i++) {
if (!ls2[i])
break
zips.push([ls1[i], ls2[i]])
}
return zips
}

Python

Similar to JavaScript, python is an interpreted language, but the solution is slightly different:

def zip(ls1, ls2):
zips = []
max_index = min(len(ls1), len(ls2))
for i in range(0, max_index):
zips.append((ls1[i], ls2[i]))
return zips

Vlang

The last solution is the Vlang solution, V is a typed language with a taste of GO and immutability, and for that, the solution has its own V way of implementing:

import math 
pub fn zip<T>(ls1 []T, ls2 []T) [][]T {
total := math.min(ls1.len, ls2.len)
return [][]T{len: total, init: [ls1[it], ls2[it]]}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kevin Da Silva

Kevin Da Silva

I'm a back-end developer, functional programming lover, fascinated by computer science and languages. From the south part of Brazil to the world