What are the advantages of using currying in a function? [duplicate]

3

I understand that, roughly simplifying, using currying is breaking a function that gets multiple arguments into smaller functions that take only parts of the original function's arguments. 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 (like Haskell). But I am not able to see advantages, whether in simplifying syntax or in performance. What would be the advantages of using a function with the currying technique instead of functions with common syntax?

PS: I did not find ideal tags

    
asked by anonymous 28.08.2017 / 21:57

1 answer

0

Currying is a technique for rewriting functions with multiple parameters such as the composition of functions of a parameter. The curry type function can only be applied 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 can be of curry type so that the return value adds (2) - note that there is no parameter y - will be an anonymous function, which is equivalent to function addition 2 (y) = 2 + y. This new function has only one parameter and corresponds to add 2 to a number. Again, this is only possible because the functions are treated as values of first importance.

It's more about functional programming where any syntax simplification is welcome, although languages like JavaScript also contain this feature, but I've never seen an application example outside the scope of its learning.

According to wikipedia :

  

The practical motivation of the technique is that frequently   obtained by applying only some of the parameters. Some   programming languages have native syntactic support   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.

    
28.08.2017 / 22:42