Functions Returning Functions

Actionscript:
  1. var connect:Function = function(xp:Number, yp:Number, col:uint=0):Function{
  2.     graphics.lineStyle(0,col);
  3.     graphics.moveTo(xp, yp);
  4.     var line:Function = function(xp:Number, yp:Number):Function{
  5.         graphics.lineTo(xp, yp);
  6.         return line;
  7.     }
  8.     return line;
  9. }
  10.  
  11. // draw a triangle
  12. connect(200,100)(300,300)(100,300)(200, 100);
  13.  
  14. // draw a box
  15. connect(100,100, 0xFF0000)(150,100)(150,150)(100, 150)(100,100);

This is one of those techniques that I never really get tired of. It's pretty useless, but fun to play around with every now and then. This draws the somewhat boring looking picture below:

[EDIT]
A few people pointed out that this could be simplified with arguments.callee... So here is an example... it does the same thing as the original code...

Actionscript:
  1. var connect:Function = function(xp:Number, yp:Number, col:uint=0):Function{
  2.     graphics.lineStyle(0,col);
  3.     graphics.moveTo(xp, yp);
  4.     return function(xp:Number, yp:Number):Function{
  5.         graphics.lineTo(xp, yp);
  6.         return arguments.callee;
  7.     }
  8. }

This entry was posted in functions, misc and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

6 Comments

  1. Posted November 23, 2009 at 11:57 am | Permalink

    I would kill you if you wrote code like that for a project I was on. :)

  2. Posted November 23, 2009 at 12:13 pm | Permalink

    ha!… I wonder if anyone has actually ever used code like that on a real project…

  3. Posted November 24, 2009 at 12:33 am | Permalink

    That’s pretty much exactly how the old AS2 Delegate class looks, if I remember correctly.

  4. Posted November 25, 2009 at 3:51 pm | Permalink

    ah yes… the delegate class… that brings back some memories…

  5. a
    Posted December 18, 2009 at 9:31 am | Permalink

    ohuuu : )
    i’m in studing python and this is really in mood as pythononian dynamic
    not really clean but tricky!

  6. sting01
    Posted January 25, 2010 at 4:20 am | Permalink

    that is called closures :)

    Common with every languages, but almost not used as most of us do not understand how they work.

    Maybe a private method is a way to describe them; but without OOP !?

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*