Unary, Binary and Variadic
Definition : The function that only applies and receives one argument value.
For example, this is a typical unary
Corresponding the defination of Binary : The function that applies and receives two argument values. We could expand this defination into the Variadic : The function that applies and recieves multiple argument values.
Currying
Definition : The currying is the process that transform a variadic into a nested unary.
It may be difficult to understand only by reading at this definition. Here is a detailed explanation by example.
We have an add function:
It applies two argument values to get its sum. But if we need to apply this function for multiple arguments, it should be rewrite as:
However, it pulls in a temporary variable sum
to store the amount while traversing the array, it also called as State
.
The one of the principles in functional programming is avoid pulling state into program for it may make effects, which causes bugs to make harder debugging.
So we should remove the state variable sum
by currying.
For example, the Binary function of sum :
We rewrite it such as:
When I want to get the sum of 2 and 3:
The function calling process:
Similarly, if we have three arguments, the currying should like:
The javascript supports variadic functions, we could derive a generator functions for currying:
So we can curry a variadic functions by function curry
;