What are the advantages of using "currying" in a function?

Asked

Viewed 93 times

3

I understand that, roughly speaking, to use currying is to break a function that takes several arguments into smaller functions that receive only parts of the arguments of the original function. Consider the code below as an example:

window.onload = function () {
  //função de somar com a sintaxe comum
  console.log("Função comum: " + soma(1,1));
  //função de somar com a sintaxe "currificada"
  console.log("Função com curry: " + somacurry(2)(2));
  //função que exibe as informações da pessoa também com curry
  console.log(pessoa("Artur")("Trapp")("21"));
}

function soma(a,b) { return a + b; }

function somacurry(a){
  return function (b) { return a + b; }
}

function pessoa(nome){
  return function (sobrenome){
    return function (idade) {
      return "Olá, meu nome é " + nome + " " + sobrenome + ", e eu tenho " + idade + " anos!";
    }
  }
}

I know that this technique is widely used in functional languages (such as Haskell). But I’m not able to see the advantages, whether in simplifying syntax or in performance. What would be the advantages of using a function with the currying technique, rather than functions with common syntax?

PS: I did not find ideal tags

1 answer

0

Currying is a technique for rewriting functions with multiple parameters such as the composition of functions of a parameter. The curry function can be applied only to a subset of its parameters. The result is a function where the parameters in this subset are now fixed as constants, and the values of the rest of the parameters are not yet specified. This new function can be applied to the remaining parameters to obtain the value of the final function. For example, a function adds(x,y) = x + y so that the return value adds(2) - note that there is no y parameter - it will be an anonymous function, which is equivalent to the added function2(y) = 2 + y. This new function has only one parameter and corresponds to adding 2 to a number. Again, this is only possible because functions are treated as primary values.

It is more focused on functional programming where any simplification of syntax is welcome, although languages such as Javascript also contain with this feature, but I’ve never seen an example of application outside the scope of this learning.

According to the Wikiedia:

The practical motivation of the technique is that often functions are used obtained by applying only some of the parameters. Some programming languages have native syntactic support for currying, so that functions with multiple parameters are expanded for reduced forms; examples include ML and Haskell. Any language that supports closures can be used to write functions with this currying technique.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.