Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flex: implementing classic curry function in actionscript?

What's the best way to implement a classic curry function in actionscript with a nice syntax?

I've tried:

Function.prototype.curry = function()
{
return "helloWorld";
}

trace((function():void {}).curry());

...approach but that didn't work.

I guess I'm stuck with a ugly approach such as:

FunctionUtils.curry(fp, ... args)

???

like image 341
Niels Bosma Avatar asked Dec 11 '08 15:12

Niels Bosma


2 Answers

I must admit I've never understood the difference between "curry" and "partial". I use the following function to do more or less what you want to do:

package {
  public function partial( func : Function, ...boundArgs ) : Function {
    return function( ...dynamicArgs ) : * {
      return func.apply(null, boundArgs.concat(dynamicArgs))
    }
  }
}

Usage examples:

var multiply : Function = function( a : Number, b : Number ) : Number { return a * b; }
var multiplyByFour : Function = partial(multiply, 4);

trace(multiplyByFour(3)); // => 12
like image 117
Theo Avatar answered Sep 28 '22 01:09

Theo


Ended up with (heavily inspired by dojo's implementation):

public static function curry(func:Function, ... args:Array):*
{
    var arity:int = func.length;
    var currying:Function = function(func:Function, arity:int, args:Array):*
    {
        return function(... moreArgs:Array):* {
            if(moreArgs.length + args.length < arity)
            {
                return currying(func, arity, args.concat(moreArgs));
            }
            return func.apply(this, args.concat(moreArgs));
        }
    }
    return currying(func, arity, args);
}

Request in the comments section to show an example of how to use this:

function foo(i:int, j:int):void
{
   trace(i+j);
}

function bar(fp:Function):void
{
   fp(2);
}

bar(FunctionUtils.curry(foo, 1)); //trace==3

Silly example, I know, but curry:ing is extremely useful. Have a look at http://www.svendtofte.com/code/curried_javascript/ for theory.

like image 20
Niels Bosma Avatar answered Sep 28 '22 00:09

Niels Bosma