Functional programming is not merely an attempt to remove side effects- it emphasizes function application and immutable values as an alternative. In fact, most functional languages are not pure. Many of the ideas that come from this point of view were borrowed by (or inspired by!) imperative programming languages.
Don't get the wrong idea- I'm not claiming functional programming is unequivocally better. I wouldn't write a kernel in Haskell (though it's been done ), but I would use functional techniques in a kernel, and I would write other kinds of programs in functional languages.
However, functional programming's focus on transforming values gives several advantages:
- functions are easier to reuse - their dependencies are explicit and can thus be explicitly exchanged
- code is easier to test - for the same reasons as reuse, it's easier to call a function with all kinds of inputs
- programs are easier to optimize - pure functions are automatically thread-safe and less coupled
- interfaces are easier to understand - everything the interface uses is right there at a glance
Most operators, even in C, are pure functions - they take inputs and give outputs without any side effects - as opposed to assembly, where most instructions destructively update their operands.
The functions you use in spreadsheets are the same - they take inputs and give outputs without any side effects. I would even bet that Excel has a function somewhere that takes a cell's contents and returns its value without changing anything.
You're right that there's a difference between describing how and what... but they're both programming. One of them is simply at a higher level of abstraction. Blueprints describe to the builders what to do, just like your call to a standard sort function describes what to do.
Shall we look at an example?
Here's quicksort in C:
Code: Select all
void qsort(int a[], int lo, int hi)
{
int h, l, p, t;
if (lo >= hi) return;
l = lo;
h = hi;
p = a[hi];
do {
while ((l < h) && (a[l] <= p))
l = l+1;
while ((h > l) && (a[h] >= p))
h = h-1;
if (l < h) {
t = a[l];
a[l] = a[h];
a[h] = t;
}
} while (l < h);
a[hi] = a[l];
a[l] = p;
qsort( a, lo, l-1 );
qsort( a, l+1, hi );
}
Code: Select all
qsort [] = []
qsort (x:xs) = qsort small ++ [x] ++ qsort large where
small = filter (< x) xs
large = filter (>= x) xs
filter [] = []
filter f (x:xs) = if f x
then x : (filter f xs)
else filter f xs