zip Function for Arrays

var one:Array = [1,2,3];
var two:Array = [10, 20, 30];

var zipOneTwo:Array = zip(one, two);

// trace each tupple
for each (var tuple:Array in zipOneTwo){
	trace(tuple);
}

/* outputs:
1,10
2,20
3,30
*/

function zip(a:Array, b:Array):Array{
	var longest:Array = (a.length >= b.length) ? a : b;
	var zipped:Array = [];
	for (var i:int = 0; i<longest.length; i++){
		zipped.push([a[i], b[i]]);
	}
	return zipped;
}

This snippet shows a function called zip that takes two arrays and returns a two dimensional array of tuples. Just imagine that each array is one side of a zipper and you’ll sort of get the idea…

I do wish flash would trace this:

[[1, 10], [2, 20], [3, 30]]

We shouldn’t have to write a utility function to see the real array structure…

I’ve been messing with haskell for a few days now… just for fun I thought I’d write a few functions inspired by it… this is the first one…

3 comments

  1. @jackson, yeah I’m aware of that… also, push() us usually slower than incrementing an index value… sometimes I write nasty looking optimized code and sometimes I try to write simple looking code… this is just an example of the latter

Leave a Reply

Your email address will not be published. Required fields are marked *