Concepts of Programming Languages

(Sean Pound) #1
15.10 Support for Functional Programming in Primarily Imperative Languages 715

|> List.filter (fun n −> n % 2 = 0)
|> List.map (fun n −> 5 * n)

The evensTimesFive function begins with the list myNums, filters out the
numbers that are not even with filter, and uses map to map a lambda expres-
sion that multiplies the numbers in a given list by five. The return value of
evensTimesFive is [10; 20].
The function composition operator builds a function that applies its left
operand to a given parameter, which is a function, and then passes the result
returned from that function to its right operand, which is also a function. So,
the F# expression (f >> g) x is equivalent to the mathematical expression
g(f(x)).
Like ML, F# supports curried functions and partial evaluation. The ML
example in Section 15.7 could be written in F# as follows:

let add a b = a + b;;
let add5 = add 5;;

Note that, unlike ML, the syntax of the formal parameter list in F# is the same
for all functions, so all functions with more than one parameter can be curried.
F# is interesting for several reasons: First, it builds on the past functional
languages as a functional language. Second, it supports virtually all program-
ming methodologies in widespread use today. Third, it is the first functional
language that is designed for interoperability with other widely used languages.
Fourth, it starts out with an elaborate and well-developed IDE and library of
utility software with .NET and its framework.

15.10 Support for Functional Programming in Primarily


Imperative Languages


Imperative programming languages have always provided only limited support
for functional programming. That limited support has resulted in little use of
those languages for functional programming. The most important restriction,
related to functional programming, of imperative languages of the past was the
lack of support for higher-order functions.
One indication of the increasing interest and use of functional program-
ming is the partial support for it that has begun to appear over the last decade in
programming languages that are primarily imperative. For example, anonymous
functions, which are like lambda expressions, are now part of JavaScript, Python,
Ruby, and C#.
In JavaScript, named functions are defined with the following syntax:

function name (formal-parameters) {
body
}
Free download pdf