ruby picture

RCR 311: Array#unzip, inverse operation to Array#zip.

Submitted by cryo (Wed Aug 10 12:26:36 UTC 2005)

Abstract

We have zip in Enumerable and Array. In the latter case there is an easy possibility for a reverse, unzip, which will (given the number of partitions) reverse the zip operation.

Problem

No real problem, except unzip has uses now and then like zip has uses now and then. It seems nice to have set of inverse functions when possible.

Proposal

An unzip method for Array, outlined below. As a partial alternative, a third argument to slice viz. a step value, so single 'zip partitions' can be extracted. Unzip could also be implemented in terms of such a slice.

Analysis

It doesn't require a language level change, like so many other things don't; zip doesn't, and in fact most methods don't. But an array of built-in methods is nevertheless seen as good, and completing methods with their inverses in the cases where it makes sense, is in my opinion desirable.

Implementation

Here is an implementation for unzip using currently available stuff:

class Array

  def unzip(level)
    res = Array.new(level, [])
    (0...size).each {|i|
      res[i % level] += [self[i]]
    }
    res
  end
end
ruby picture
Comments Current voting
I'm not sure what I think of this. It feels like this should be able to be done with #partition, but blinker me if I can figure out how. Array#unzip also -- to me -- doesn't seem to suggest anything useful. --Austin


Haskell also has these, zip and unzip (which always zips two lists, and unzips into two lists; but zip3/unzip3 are also there). I realise I am not suggesting this to solve a present problem, but more to 'complete' the interface, providing an inverse for something already there.

--Sune.


test comment -- please ignore


Strongly opposed 0
Opposed 0
Neutral 2
In favor 5
Strongly advocate 1
ruby picture
If you have registered at RCRchive, you may now sign in below. If you have not registered, you may sign up for a username and password. Registering enables you to submit new RCRs, and vote and leave comments on existing RCRs.
Your username:
Your password:

ruby picture

Powered by .