Sure, for example, the queueing system in my current shmup engine, I want to be able to pull a sprite off of a given bucket if it's inactive, or return null if it is not.
Originally, I had this code, which works just fine,
Code: Select all
function takeBadGuy():Character
{
var free:Array = badGuys.filter(isInactive);
if (free.length > 0)
{
var c:Character = free.shift();
c.active = true;
return c;
}
return null;
}
Except that I needed to rewrite the same bit of code for egoBullets, pickUps, and any other new buckets I added, so I rewrote it like so:
Code: Select all
public function curryTake(arr:Array):Function
{
return function():Character
{
var free:Array = arr.filter(isInactive);
if (free.length > 0)
{
var c:Character = free.shift();
c.active = true;
return c;
}
return null;
}
}
public var takeBadGuy:Function = curryTake(badGuys);
So, takeBadGuy is defined as the returned value of curryTake, with the argument of the array badGuys. The array argument is bound to the value arr in the function defined in the body of curryTake.
So, now I just add more buckets, like
Code: Select all
public var takeBullet:Function = curryTake(bullets);
Now, I could do all of this by just making a queue object. Then I could pack in both the list of objects and the methods to operate on them. In fact, if my queues ever needed to be more complex, I probably would. However, at this level of complexity, it's 6 on one side, half a dozen on the other. Additionally, in some languages, like Python, additional overhead is incurred for each additional function call and object attribute dereference. I could argue that in this case, currying might save me a little in performance.
Other languages, like Scheme, don't have objects (sure there are extensions for objects, but let's just assume core), so currying functions is a great tool, right up there with macros. You can use objects if you prefer, but currying is not just a cute trick.