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?
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
andadder
look very similar.add
takes 2 parameters and adds them, theadder
returns a function that adds the parameter ofadder
to its own parameter.The transformation of
add
toadder
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.