Concepts of Programming Languages

(Sean Pound) #1

718 Chapter 15 Functional Programming Languages


nor do they take the same amount of time to produce. In fact, because of the
necessity of dealing with variables, imperative programs have many trivially
simple lines for initializing and making small changes to variables.
Execution efficiency is another basis for comparison. When functional
programs are interpreted, they are of course much slower than their com-
piled imperative counterparts. However, there are now compilers for most
functional languages, so that execution speed disparities between functional
languages and compiled imperative languages are no longer so great. One
might be tempted to say that because functional programs are significantly
smaller than equivalent imperative programs, they should execute much
faster than the imperative programs. However, this often is not the case,
because of a collection of language characteristics of the functional lan-
guages, such as lazy evaluation, that have a negative impact on execution
efficiency. Considering the relative efficiency of functional and imperative
programs, it is reasonable to estimate that an average functional program
will execute in about twice the time of its imperative counterpart (Wadler,
1998). This may sound like a significant difference, one that would often lead
one to dismiss the functional languages for a given application. However,
this factor-of-two difference is important only in situations where execu-
tion speed is of the utmost importance. There are many situations where a
factor of two in execution speed is not considered important. For example,
consider that many programs written in imperative languages, such as the
Web software written in JavaScript and PHP, are interpreted and therefore
are much slower than equivalent compiled versions. For these applications,
execution speed is not the first priority.
Another source of the difference in execution efficiency between functional
and imperative programs is the fact that imperative languages were designed
to run efficiently on von Neumann architecture computers, while the design
of functional languages is based on mathematical functions. This gives the
imperative languages a large advantage.
Functional languages have a potential advantage in readability. In many
imperative programs, the details of dealing with variables obscure the logic of
the program. Consider a function that computes the sum of the cubes of the
first n positive integers. In C, such a function would likely appear similar to
the following:

int sum_cubes(int n){
int sum = 0;
for(int index = 1; index <= n; index++)
sum += index * index * index;
return sum;
}

In Haskell, the function could be:

sumCubes n = sum (map (^3) [1..n])
Free download pdf