0

I am having hard time understanding currying through several sources on web . Isn't there more intuitive example of currying?

Also, what are its advantages over traditional programming paradigm ? Is currying possible to achieve on non-functional programmming?

Sarit Adhikari
  • 1,344
  • 2
  • 16
  • 28

1 Answers1

3

Imagine a function with multiple parameters add(a,b) = a + b. This function adds two numbers. Now imagine, in some context you need a function that takes just one parameter and you'd like to have a function that adds 5. That function could look like this: adds5(x) = 5 + x.

Now, in some contexts you'd need a function that adds 5, in other contexts one that adds 10. So instead of writing various functions that do the same just with other constant, you can write a function that does return a function that adds a constant that is a parameter to the first function: adder(a) = (b) = a + b.

The function add and adder look very similar. add takes 2 parameters and adds them, the adder returns a function that adds the parameter of adder to its own parameter.

The transformation of add to adder is called currying.

Since this is so much related to functions, I'd say that when there is currying, then it is functional programming. You can do functional programming in any programming language - after all, all Turing complete languages are equivalent ;-) , but in functional languages that support functions as first class citizens, it is much easier.

Gregor Raýman
  • 3,051
  • 13
  • 19
  • Thanks for beautiful explanation . But there's one thing I can't get out of my head. If a function with multiple parameters can achieve the same result, what is the point in defining a function returning a function to complicate the proceeding? – Sarit Adhikari Jun 11 '15 at 15:00
  • 1
    There is indeed no benefit, if all you need is a function with multiple parameters. It is only beneficial when you need a function with fewer parameters than the original function. Imagine a function that fills a shape on the screen with a color. The function will have two parameters shape and the color. In your application you can show a color chooser widget that should color the selected shape with the color. The color chooser callback has however just one parameter - the color. So with currying of the first function you can easily create the needed callback for the color chooser. – Gregor Raýman Jun 11 '15 at 15:11
  • @SaritAdhikari [This](http://stackoverflow.com/q/12413495/1346276) is a question asking the same for Haskell, maybe it's helpful. The main point, IMHO, is, that it's useful for partial application. – phipsgabler Jun 11 '15 at 19:19