Function Programing Language
Function Programing Language
BENJAMIN GOLDBERG
New York University ^[email protected]&
let x 5 f~y!
then this would introduce the name x
n!5 H 1 if n 5 0
n~n – 1!! otherwise
and assert that the equation x 5 f(y)
is true. There is no notion of a memory In a functional language the executable-
cell, and certainly no notion that some- definition of factorial is generally writ-
how later in the program x might ten as
change (so that the equation would be-
come false). let factorial~n!5
If one were to write
if n 55 0 then 1
let x 5 x 1 1 else n*factorial~n 2 1!
and follows directly from the formal def- In this case, the parameters to com-
inition (where 55 is the equality com- pose, f, and g, must both be functions.
parison operator). In addition, the value returned by
This is in contrast to the C version compose, namely h, is also a function,
defined by the equation h(x) 5
int fac~int n! f(g(x)).
$int prod 5 1; As another example of the use of
for ~int i 5 0; higher-order functions, consider again
the factorial function. It might be ar-
i ,5 n; i11) gued that the formal definition of facto-
prod 5 prod * i ; rial given above was tailored to suit the
} recursive nature of the definition of fac-
torial in the functional language, and
which can be understood only by tracing that a more reasonable and common
the sequence of modifications to the vari- definition of factorial is
ables prod and i during the iteration.
Functional languages exhibit a prop-
Pi
n
erty called referential transparency,
which essentially means that “like can n!5
be replaced by like.” For example, the i51
expression
P f~i!
n
let x 5 f~y!
in x 1 x
i5m
in which the two original occurrences of
f(y) are replaced by x. This follows
directly from the fact that the declara- for some initial value m, some final
tion x5 f(y) denotes an equation in a value n, and some function f. In a func-
functional language, but certainly tional language, & can easily be written
would not be the case in an imperative as a higher-order function of three pa-
language. In an imperative language, rameters, m, n, and f, defined by
the first call to f might change the
value of a variable used in the second prod~m, n, f !
call to f. This kind of behavior, known 5 if m 55 n then f~m!
as a side-effect, cannot occur in a func-
else f~m! p prod~m, n, f!
tional language.
where 55 is the equality comparison
operator. Thus, factorial can be defined
HIGHER-ORDER FUNCTIONS
as:
Most functional languages support func-
tions that operate over functions—that let fac~n! 5 let f~i! 5 i
is, functions that take other functions in prod~1,n,f!
as parameters and/or return functions
as values. A simple example is the com- and the power function, computing xn,
pose function, defined as can be defined as