o r3: Redundant function elimination
x.(e x) e, if x is not free in e
o An expression that can no longer be reduced is
said to be in normal form
Examples:
(x.( y.x + y) 5)(( y.y * y) 6) =
(x.x + 5)(( y.y * y) 6) =
(x.x + 5)(6 * 6) =
((6 * 6) + 5)
(λx. λy.x + y) 3 4
λy.(3 + y) 4
(3 + 4)
7
5.3. Python Lambda Expression
Python’s lambda creates anonymous
functions
>>> myf = lambda z: z * 42
>>> f(3)
126
A. Bellaachia Page: 9
Only one expression in the lambda body; its
value is always returned.
Examples:
>>> def f (x): return x**2
...
>>> print f(8)
64
>>>
>>> g = lambda x: x**2
>>>
>>> print g(8)
64
>>> f = lambda y: y * y
>>> g = lambda y: f(x) + y
>>> x=6
>>> f(6)
36
>>> g(5)
41
>>>
>>> myLamFunction = lambda a, b: a+b
>>> myLamFunction(2,3)
5
>>>
A. Bellaachia Page: 10
6. Functions in FPLs
In a functional language, the basic unit of computation is
the FUNCTION.
The function definitions typically include a name for the
function, its associated parameter list, and the expressions
used to carry out the computation.
A function computes a single value based on 0 or more
parameters.
Though the parameters of a function look like
variables in an imperative language, they are
different in that they are not subject to having
their value changed by assignment - i.e. they
retain their initial value throughout the
computation of the function.
Pure functional languages don't need an
assignment statement.
Function construction: given one or more functions as
parameters, as well as a list of other parameters,
construction essentially calls each function and passes it the
list of "other" parameters.
Function composition: applying one function to the result
of another. E.g. square_root(absolute_value(-3))
A. Bellaachia Page: 11
Apply-to-all functions: takes a single function as a
parameter along with list of operand values. It then applies
the function to each parameter, and returns a list containing
the results of each call.
Example:
suppose applyall carried this out with the function
square and the data list (1 2 3).
The result would be a list with the values from
square(1), square(2), and square(3), i.e. (1 4 9)
Example: A LISP factorial function, illustrating use of
conditional expressions and recursion for iteration
(DEFUN FACT (X)
(IF (= X 0)
1
(* X (FACT (- 1 X)) )
)
)
A. Bellaachia Page: 12