I have been dabbling with haskell lately and will update some functional concepts.
Currying: What is it?
Currying is parameter application to functions. In c++, we can have arguments passed to a function.
int foo(type par1, type par2, ...){
//perform operations on the par's
}
This is really great, but in functional programming paradigm; every function takes only a single argument. Oh no! what are we to do? Well here is where currying comes to the rescue. If you pass a function multiple parameters in functional programming languages, such as scheme and haskell, they perform currying of the function.
How it works
The function takes the first parameter, then another function is applied to the 2nd parameter.
>let x3 x y z = x*y*z
>x3 2 3 4
24
The above function takes 3 parameters and multiplies them together. This is just repeated application of the * function, right? I could have said (x*y)*z.
This is exactly what currying is doing. Internally I look at it like this
func1 = x3 (x)
func2 = func1(y)
func3 = func2(z)
The function is applied to one argument, the applied function is then called on the 2nd argument and so on.
This can be used with partial functions to create simple and intuitive data flow mechanisms.
No comments:
Post a Comment