Monday, March 31, 2014

How to zip in Clojure

In programming, there's time when we have 2 arrays and we want values at the same index of both arrays to have operation on each other producing an array of result. In imperative style, we have to setup a temporary counter variable to store index the current operation is on, increment it until reaching the last value of an array. For example, we want to sum values of each index.

In functional style, there's a function called 'zip' (Haskell, Ruby) which allows us to pair up values of each index preparing to apply operation on each pair later.

In Haskell, there's even 'zipWith' which apply operation on the pair immediately instead of producing an intermediate array.

But when it comes to Clojure, I wasn't be able to find a function in its standard library with the same behavior. The closest I could find is 'zipmap' that returns back a map which is not exactly what I want. We definitely can work around a little bit to get a vector.

But as you can see, it doesn't preserve the order of an original vectors.