Concepts of Programming Languages

(Sean Pound) #1

716 Chapter 15 Functional Programming Languages


An anonymous function is defined in JavaScript with the same syntax, except
that the name of the function is omitted.
C# supports lambda expressions that have a different syntax than that of
C# functions. For example, we could have the following:

i => (i % 2) == 0

This lambda expression returns a Boolean value depending on whether the
given parameter (i) is even (true) or odd (false). C#’s lambda expressions
can have more than one parameter and more than one statement.
Python’s lambda expressions define simple one-statement anonymous
functions that can have more than one parameter. The syntax of a lambda
expression in Python is exemplified by the following:

lambda a, b : 2 * a – b

Note that the formal parameters are separated from function body by a colon.
Python includes the higher-order functions filter and map. Both often
use lambda expressions as their first parameter. The second parameter of these
is a sequence type, and both return the same sequence type as their second
parameter. In Python, strings, lists, and tuples are considered sequences. Con-
sider the following example of using the map function in Python:

map(lambda x: x ** 3, [2, 4, 6, 8])

This call returns [8, 64, 216, 512].
Python also supports partial function applications. Consider the following
example:

from operator import add
add5 = partial (add, 5)

The from declaration here imports the functional version of the addition oper-
ator, which is named add, from the operator module.
After defining add5, it can be used with one parameter, as in the following:

add5(15)

This call returns 20.
As described in Chapter 6, Python includes lists and list comprehensions.
Ruby’s blocks are effectively subprograms that are sent to methods,
which makes the method a higher-order subprogram. A Ruby block can be
converted to a subprogram object with lambda. For example, consider the
following:

times = lambda {|a, b| a * b}
Free download pdf