Haskell Inspired zipWith() Function

initOperators();

trace(zipWith("-", [1,2,3], [1,2,3]));
trace(zipWith("+", [1,2,3], [1,2,3]));
trace(zipWith("*", [1,2,3], [1,2,3]));
trace(zipWith("+", [1,1,1,3], [4,5,6,7]));
trace(zipWith("<<", [2, 4], [1,1]));
/*
outputs:

0,0,0
2,4,6
1,4,9
5,6,7,10
4,8
*/

function zipWith(op:String, a:Array, b:Array):Array{
    var aLeng:int = a.length;
    var bLeng:int = b.length;
    var leng:Number = (aLeng < bLeng) ? aLeng : bLeng;
    var zipped:Array = [];
   
    if (!this[op])return [];
   
    for (var i:int = 0; i<leng; i++){
        zipped[i]=this[op](a[i], b[i]);
    }
    return zipped;
}

function initOperators():void{
    this["+"]=function(a:Number, b:Number):Number{ return a + b };
    this["-"]=function(a:Number, b:Number):Number{ return a - b };
    this["/"]=function(a:Number, b:Number):Number{ return a / b };
    this["*"]=function(a:Number, b:Number):Number{ return a * b };
    this["%"]=function(a:Number, b:Number):Number{ return a % b };
   
    this["&"]=function(a:Number, b:Number):Number{ return a & b };
    this["<<"]=function(a:Number, b:Number):Number{ return a << b };
    this["|"]=function(a:Number, b:Number):Number{ return a | b };
    this[">>"]=function(a:Number, b:Number):Number{ return a >> b };
    this[">>>"]=function(a:Number, b:Number):Number{ return a >>> b };
    this["^"]=function(a:Number, b:Number):Number{ return a ^ b };
}

This snippet is basically like the haskell zipWith() function. It can combines two arrays into one array given a single function. In this case I defined a bunch of operator functions, but it would work with any kind of function that takes two arguments and returns a value. You could extend this to work with strings and do other strange things I guess.

If you have yet to go play with haskell … go do it now.

2 comments

  1. Haskell zipWith does not merge two lists into 1 list using a function, rather it takes an initial value, a function and accumulates and return the function result over all values.

Leave a Reply

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