Introduction
Most of my background is in imperative programming using C# and C++. Presently I am learning functional programming, and so created a simple program to demonstrate higher order functions. Functional programming uses declarative code, because this allows the developer to focus more on what he wants the program to do rather than how exactly the developer wants the solution to be constructed. Functional programs make extensive use of higher-order functions, which are functions that can take other functions as arguments or return them as results.
Using the code
Imagine you wanted to create a program that performs two different calculations, but the calculations differ only by the operation performed and the initial value. Consider these two calculations:
3 + (4 + (5 + (6 + (7 + (8 + 0)))))
And this,
3 * (4 * (5 * (6 * (7 * (8 * 1)))))
A traditional imperative software developer could possibly decide to create a base class called Calculation, and several derived classes specified by names such as Multiplication and Addition. The problem with this solution is that it is much too complicated for such a basic requirement. Instead, let`s use higher-order functions:
Here is the recursive function that is operation agnostic:
private static int PerformAggregation(Func<int,> operation, int initial, int start, int end)
{
if (start > end)
return initial;
int intermediate = PerformAggregation(operation, initial, start + 1, end);
return operation(start, intermediate);
}
</int,>
To perform the operations, the developer can use generic delegates:
Func<int,> aggregateMethod1 = delegate(int i, int j)
{
return i + j;
};
Func<int,> aggregateMethod2 = delegate(int i, int j)
{
return i * j;
};
Or lambda functions:
Func<int,> aggregateMethod1 = (i, j) => i + j;
Func<int,> aggregateMethod2 = (i, j) => i * j;
The developer could then make use of these functions like so:
Console.WriteLine("Addition: {0}", PerformAggregation(aggregateMethod1, 0, 3, 8));
Console.WriteLine("Multiplication: {0}", PerformAggregation(aggregateMethod2, 1, 3, 8));
Points of Interest
Object-oriented imperative programs are constantly changing state, so many extra precautions need to be taken so that no two processes or threads are in the same critical section at the same time. Functional programs use immutable objects to perform their operations, so this allows for parallelism without requiring all the extra work of creating semaphores to prevent race conditions.
As I have been learning functional programming, I've written some simple test programs like the one above. Hopefully you will find this article helpful!
History
- 2013.08.30: Initial post.
- 2013.09.13: Added sample on use of functions.
References
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.