Title: Functional Programming Basics
1Functional Programming Basics
- Correctness gt Clarity gt Efficiency
2- Function Definition
- Equations Recursion
- Higher-order functions
- Function Application
- Computation by expression evaluation
- Choices parameter passing
- Reliability
- Types
- Strong typing, Polymorphism, ADTs.
- Garbage Collection
3Imperative Style vs Functional Style
- Imperative programs
- Description of WHAT is to be computed is
inter-twined with HOW it is to be computed. - The latter involves organization of data and the
sequencing of instructions. - Functional Programs
- Separates WHAT from HOW.
- The former is programmers responsibility the
latter is interpreters/compilers responsibility.
4- Functional Style
- Value to be computed a b c
- Imperative Style
- Recipe for computing the value
- Intermediate Code
- T a b T T c
- T b c T a T
- Accumulator Machine
- Load a Add b Add c
- Stack Machine
- Push a Push b Add Push c Add
5GCD functional vs imperative
- fun gcd(m,n)
- if m0 then n
- else gcd(n mod m, m)
- function gcd(m,n int) int
- var pmint
- begin while mltgt0 do
- begin
- pm m m n mod m n pm
- end
- return n
- end
6Pitfalls Sequencing
- (define (factorial n)
- (define (iter prod counter)
- (if (gt counter n) prod
- (iter ( counter prod)
- ( counter 1) ) ))
- (iter 1 1)
- )
7- (define (factorial n)
- (let ((prod 1)(counter 1))
- (define (iter)
- (if (gt counter n) prod
- (begin
- (set! prod ( counter prod))
- (set! counter ( 1 counter))
- (iter))
- ))
- ))
8Function
- A function f from domain A to co-domain B,
denoted f A -gt B, is a map that associates with
every element a in A, a unique element b in B,
denoted f(a). - Cf. Relation, multi-valued function, partial
function, - In mathematics, the term function usually
refers to a total function in computer science,
the term function usually refers to a partial
function.
9Representation of functions
- Intensional Rule of calculation
- fun double n 2 n
- fun double n n n
- Extensional Behavioral (Table)
- Equality
- f g iff for all x f(x) g(x)
10Expression Evaluation Reduction
- fun double x x x
- double ( 3 2)
- double(6) (32) (32) (32) o
- 6 6 6 (3 2) 6
o - Applicative-Order Normal-Order Lazy
- (call by value) (call by name)
(call by need)
11Role of variable
- In functional style, a variable stands for an
arbitrary value, and is used to abbreviate an
infinite collection of equations. - 0 0 0
- 0 1 1
-
- for all x 0 x x
- In imperative style, a variable is a location
that can hold a value, and which can be changed
through an assignment. - x x 1
- Functional variable can be viewed as assign-only-
once imperative variable.
12Referential Transparency
- The only thing that matters about an expression
is its value, and any sub-expression can be
replaced by any other expression equal in value. - The value of an expression is independent of its
position only provided we remain within the
scopes of the definitions which apply to the
names occurring in the expression.
13Examples
- let x 5 in
- x let x 4 in x x
- val y 2 val y 6
-
- var x int
- begin
- x x 2 x x 1
- end
-
- address of x value stored in location for
x
14- (x2) /\ (xygt2) (2ygt2)
- vs
- fun f (x int) int
- begin y y 1
- return ( x y)
- end
-
- (y0) /\ (z0) /\ (f(y)f(z))
- false
- (y0) /\ (z0) /\ (f(z)f(z))
- / (y0) /\ (z0) /\ (f(z)1)
15- Common sub-expression elimination is an
incorrect optimization without referential
transparency. - In functional style
- E E let x E in x x
- In imperative style
- return (x x)
- /
- y x return (y y)
- Parallel evaluation of sub-expressions possible
with referential transparency.
16By GUY STEELE
17Strict vs Non-strict
- A function is strict if it returns well-defined
results only when the inputs are well-defined. - E.g., In C, and are strict, while
and are not. - E.g., In Ada, and and or are strict, while
and then and or else are not. - E.g., constant functions are non-strict if called
by name, but are strict if called by value.
18Traditional Benefits of Programming in a
Functional Language
- Convenient to code symbolic computations and list
processing applications. - Automatic storage management
- Improves program reliability.
- Enhances programmer productivity.
- Abstraction through higher-order functions and
polymorphism. - Facilitates code reuse.
- Ease of prototyping using interactive development
environments.
19Global Summary
Programming Languages
Imperative
Functional
Logic
C, Pascal
Prolog
Dynamically Typed (Meta-programming)
Statically Typed (Type Inference/Reliable)
LISP, Scheme
Lazy Eval / Pure
Eager Eval / Impure
Haskell
SML
20Higher-Order Functions
21Higher-Order Functions
- A function that takes a function as argument
and/or returns a function as result is called a
higher-order function or a functional. - ML/Scheme treat functions as first-class
(primitive) values. - Can be supplied as input to functions.
- Not allowed in Ada.
- Can be created through expression evaluation.
- Not allowed in C/Java/LISP.
- Can be stored in data structures.
22Nested Functional Static Scoping
- fun f x
- let
- val g fn y gt 8 x y
- in g
- end
- val h f 5
- h 2
- Breaks stack-based storage allocation Requires
heap-based storage allocation and garbage
collection (Closures)
23ML function definitions
- fun elem_to_list
- elem_to_list (ht)
- h (elem_to_list t)
- elem_to_list a a
- fun inc_each_elem
- inc_each_elem (ht)
- (h1) (inc_each_elem t)
- inc_each_elem 1,2,3 2,3,4
24Abstracting Patterns of Recursion
- fun map f
- map f (ht)
- (f h)(map f t)
- fun elem_to_list x
- map (fn x gt x) x
- val inc_each_elem
- map (fn x gt x1)
25Functionals Reusable modules
- Libraries usually contain functionals that
can be customized. - sort order list
- Can be used for
- descending_order_sort
- ascending_order_sort
- sort_on_length
- sort_lexicographically
- sort_on_name
- sort_on_salary
- ...
26Orthogonality
- Instead of defining related but separate
functions such as - remove-if remove-if-not
- process_till_p process_till_not_p
- define one generalized functional complement.
- Refer to CommonLISP vs Scheme
27Currying
- fun plus (x, y) x y
- fun add x y x y
- plus (5,3) 8
- add 5 3 8
- add 5 (fn x gt 5x)
- Curried functions are higher-order functions that
consume their arguments lazily. - All ML functions are curried !
28Significance of Curried Functions
- Supports partial evaluation.
- Useful for customizing (instantiating) general
purpose higher-order functions (generics). - Succinct definitions.
- Denotational (Semantics) Specifications.
- One-argument functions sufficient.
- All ML functions are unary.
29- fun curry f
- fn x gt (fn y gt f(x,y))
- fun uncurry f
- fn (x,y) gt (f x y)
-
- curry (uncurry f) f
- uncurry (curry f) f
- (Higher-order functions)
30Classification of functions
- Primitive
- , , - , etc.
- Higher-order
- Hierarchical
- (sort order list),(filter pred list)
- Self-applicable
- map , id (E.g., (map (map f)) )
- fun double f f o f
-
composition
31From Spec. to Impl.
- Spec
- (sqrt x) gt 0 /\ (sqrt x)2 x
- Computable Spec
- (sqrt x) gt 0 /\
- abs((sqrt x)2 - x) lt eps
- Improving Approximations (Newtons method)
- y(n1) (y(n) x / y(n)) / 2
32- fun improve x y
- ( y x / y) / 2.0
- val eps 1.0e5
- fun satis x y
- abs( yy - x) lt eps
- fun until p f y
- if p y then y
- else until p f (f y)
- fun sqrt x
- until (satis x) (improve x) 1.0
33ML Meta Language
- Initial Domains of Application
- Formal Specification of Languages
- Theorem Proving
- Theorems are values (terms) of an ADT.
- Theorems can only be constructed using the
functions supported by the ADT (no spoofing). - ML is a mathematically clean modern programming
language for the construction of readable and
reliable programs. - Executable Specification.
34- Symbolic Values
- Recursive Definitions
- Higher-Order Functions
- Strongly Typed
- Static Type Inference
- Polymorphic Type System
- Automatic Storage Management
- Pattern Matching
- ADTs Modules and Functors
- Functional Imperative features
35- fun len 0
- len (xxs)
- 1 len xs
- (define (len xs)
- (if (null? xs)
- 0
- ( 1 (len (cdr xs)))
- )
- )