Currying

Currying

> LeekScript Tutorial

*This page is partially obsolete. In Leekscript, currying is only used to make the code more readable, it no longer saves operations since the cost of a call to a function is reduced to 1 regardless of the number of parameters. *

In functional programming, currying refers to the operation that takes a multi-argument function to a one-argument function and returns a function that takes the rest of the arguments. The reverse operation is obviously possible and is called decurryfication.

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 the sum of the 2:

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

Turns into curried method

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

Example of use

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

//Curry method var add1 = add_curried(1); var sum = add1(3);

This example is just to simply show how it works, in this case there is no point in going through currying. Let's see another more interesting example. Imagine that we have an array of n numeric elements and we want to add 1 to all the elements.

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

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

The advantage here is seen in terms of optimization, in the loop instead of calling a function with 2 parameters, we only call a function with one parameter. The greater the number of elements in the array, the greater the gain.

When is it worth currying?

As we have seen previously, the main use is for functions called in loops and one or more of whose parameters do not depend on the loop. Memoization is a perfect example of use.

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

If we call this function in a loop, the two operations will weigh us down! Currification can help us:

Our function returns another function, which can use the parameters of the first one, it's a bit difficult to understand the first time, but well used this method is very effective! A little exercise: we can optimize this function even more, it's up to you to find out how!