What is Currying?

Being a (fairly) little-known concept in programming, currying seems worthy of its own blog post.

In general

Simply put, currying is where:

Methods may define multiple parameter lists. When a method is called
with a fewer number of parameter lists, then this will yield a function
taking the missing parameter lists as its arguments.
scala-lang.org

In PHP

Currying is not a built-in feature of PHP. However, as outlined in quite some depth in this excellent post over at Zaemis’ blog, it is possible to emulate much of the functionality of currying in PHP (or at least, in PHP v5.3 and above) through use of closures.

An example

My favourite example from Zaemis’ blog post (which I recommend you read) is as below:

  $userPercent = 0.5;   $userList = array_filter($percentVowels,       function($percent) use ($userPercent) {           return ($percent >= $userPercent);       });
It showed an anonymous function being used with array_filter() to filter an array. The array is filtered based on a dynamic value, and a closure is used to “inject” the threshold rather than using a global statement. The same could also be accomplished with currying.

The problem is array_filter() expects a callback function that accepts one argument–the current array element. Currying will allow us to prepare the function with the sorting threshold, and the intermediate function can be used as the callback.

  function callback($userPercent) {       return function($percent) use ($userPercent) {           return ($percent >= $userPercent);       };   }   $userList = array_filter($percentVowels, callback(0.5));

Cheers, Dan Phillimore

About the author

  • Dan has spent the past 10 years developing specialist software, using everything from x86 assembly to C++ and VB. For the past few years he has focused on JavaScript development of high-performance virtual machines for the modern web and developing bespoke modern websites using the LAMP stack.
  • When he is not working on the next web-based OS, he spends his time out with friends, his girlfriend Jen or planning to buy an American muscle car.
You can leave a response, or trackback from your own site.

Leave a Reply

Powered by WordPress | Design by OVMS, based on AnimeStar (Best MMORPGs | Thanks to MMORPG List, VPS Hosting and Website Hosting)