Currying

Currying

> LeekScript Tutorial

This page is partly obsolete. In LeekScript, currying now only serves to make code more readable: it no longer saves operations, since the cost of a function call became 1 regardless of the number of parameters.

In functional programming, currying is the operation that turns a function taking several arguments into a function that takes one argument and returns a function taking the rest of the arguments. The reverse operation is of course possible, and is called uncurrying.

The term comes from the name of the American mathematician Haskell Curry.

Example in LeekScript

Let's take a function that takes 2 arguments and returns their sum:

function add(x, y) { return x + y; }

It becomes a curried method

function add_curried(x) { return function(y) { return x + y; }; }

Usage example

//Classic method var total = add(1, 3);

//Curried method var add1 = add_curried(1); total = add1(3);

This example only shows, in simple terms, how it works: in this case, there's no point in currying. Let's look at another, more interesting example. Imagine we have an array of n numeric elements and we want to add 1 to every element.

//Classic method for(var key:var element in array) { array[key] = add(1, element); }

//Curried method var add1 = add_curried(1); for(var key:var element in array) { array[key] = add1(element); }

The advantage here is in terms of optimization: inside the loop, instead of calling a function with 2 parameters, we only call a function with one parameter. The more elements there are in the array, the bigger the gain.

When is currying worth it?

As we saw earlier, the main use is for functions that are called inside loops and that have one or more parameters that don't depend on the loop. Memoization is a perfect use case.

Take for example our lineOfSight function with memoization (defined here):

If we call this function in a loop, those two operations will weigh on us! Currying can help:

Our function returns another function, which can use the parameters of the first one. It's a bit hard to grasp the first time, but used well, this technique is very effective! A little exercise: this function can be optimized even further. Up to you to figure out how!