Programming Language:: Design and Implementation
Programming Language:: Design and Implementation
Functional Programming
Session 3
Functional Programming
In contrast to procedural languages, functional programs don't
concern themselves with state and memory locations. Instead, they
work exclusively with values, and expressions and functions which
compute values.
- Functional programming is not tied to the von Neumann machine.
- It is not necessary to know anything about the underlying hardware
when writing a functional program, the way you do when writing an
imperative program.
- Functional programs are more declarative than procedural ones; i.e.
they describe what is to be computed rather than how it should be
computed.
Functional Languages
Common characteristics of functional programming languages:
A function produces result values that lie in a target set (or range).
More on functions
A function must not map an input value to more than one output
value. Example:
More on functions...
If a function F maps every element in the domain to some element
in the range, then F is total. I.e. a total function is defined for all
arguments.
More on functions...
A function that is undefined for some inputs, is called partial.
double x = 2 * x
even x = x mod 2 == 0
isHandsome x = if isBald x
then True
else False
Specifying functions…
Graphically:
The graphical view is a notational variant of the
intentional view.
Function Application
The most important operation in a functional program is function
application, i.e. applying an input argument to the function, and
retrieving the result:
double x = 2 * x
even x = x mod 2 == 0
double 5 10
even 6 True
Function Composition
Function composition makes the result of one function
application the input to another application:
double x = 2 * x
even x = x mod 2 == 0
double x = 2 * x
even x = x mod 2 == 0
even (double 5)
even (2 * 5)
even 10
10 mod 2 == 0
0 == 0 True
Referential Transparency
So, isn't Pascal referentially transparent??? Well, sometimes, yes, but not
always. If a Pascal function ƒ has side-effects (updating a global variable,
doing input or output), then ƒ(3) + ƒ(3) may not be the same as 2* ƒ(3).
I.e. The second ƒ(3) has a different meaning than the first one.
var G: integer;
Function f (n:integer) : integer;
begin G:= G+1; f:=G+n; end;
begin begin
G:= 0; G:= 0;
print f(3) +f(3); print 2*f(3);
{print 4+5=9} {print 2*4=8}
end end
Referential Transparency
Furthermore, in many imperative languages the order in which the
arguments to a binary operator are evaluated are undefined.
var G: integer;
Function f (n:integer) : integer;
begin G:= G+1; f:=G+n; end;