Download Function

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Tail call wikipedia , lookup

Lambda calculus wikipedia , lookup

Combinatory logic wikipedia , lookup

Lambda calculus definition wikipedia , lookup

Closure (computer programming) wikipedia , lookup

Currying wikipedia , lookup

Lambda lifting wikipedia , lookup

Anonymous function wikipedia , lookup

Falcon (programming language) wikipedia , lookup

Standard ML wikipedia , lookup

Transcript
Functional Programming Basics
Correctness > Clarity > Efficiency
cs7120 (Prasad)
L1-FP-HOF
1
• Function Definition
• Equations ; Recursion
• Higher-order functions
• Function Application
• Computation by expression evaluation
• Choices : parameter passing
Reliability
Types
Strong typing, Polymorphism, ADTs.
Garbage Collection
cs7120 (Prasad)
L1-FP-HOF
2
Imperative 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 programmer’s responsibility; the
latter is interpreter’s/compiler’s responsibility.
cs7120 (Prasad)
L1-FP-HOF
3
• 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;
cs7120 (Prasad)
Add; Push c; Add;
L1-FP-HOF
4
GCD : functional vs imperative
fun gcd(m,n) =
if m=0 then n
else gcd(n mod m, m);
function gcd(m,n: int) : int;
var pm:int;
begin while m<>0 do
begin
pm := m; m := n mod m;
end;
return n
end;
cs7120 (Prasad)
L1-FP-HOF
n := pm
5
Pitfalls : Sequencing
(define (factorial n)
(define (iter prod counter)
(if (> counter n) prod
(iter (* counter prod)
(+ counter 1) ) ))
(iter 1 1)
)
cs7120 (Prasad)
L1-FP-HOF
6
(define (factorial n)
(let ((prod 1)(counter 1))
(define (iter)
(if
(> counter n)
prod
(begin
(set! prod (* counter prod))
(set! counter (+ 1 counter))
(iter))
))
))
cs7120 (Prasad)
L1-FP-HOF
7
Function
• A function f from domain A to co-domain
B, denoted f : A -> 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.
cs7120 (Prasad)
L1-FP-HOF
8
Representation of functions
• Intensional :
Rule of calculation
fun double n = 2 * n;
fun double n = n + n;
• Extensional : Behavioral (Table)
… -2 -1 0
1 2 3 …
… -4 -2 0
2 4 6 …
• Equality:
f = g iff for all x: f(x) = g(x)
cs7120 (Prasad)
L1-FP-HOF
9
Expression Evaluation : Reduction
fun double x = x + x;
double ( 3 * 2)
double(6)
6+6
(3*2) + (3*2) (3*2) + o
6 + (3 * 2)
Applicative-Order
Normal-Order
(call by value)
(call by name)
cs7120 (Prasad)
L1-FP-HOF
6 + o
Lazy
(call by need)
10
Role of variable
• In functional style, a
variable stands for an
arbitrary value, and is
used to abbreviate an
infinite collection of
equations.
• In imperative style, a
variable is a location
that can hold a value,
and which can be
changed through an
assignment.
x := x + 1;
0+0=0
0+1=1
…
for all x : 0 + x = x
cs7120 (Prasad)
• Functional variable can be
viewed as assign-only- once
imperative variable.
L1-FP-HOF
11
Referential Transparency
• The only thing that matters about an
expression is its value, and any subexpression 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.
cs7120 (Prasad)
L1-FP-HOF
12
Examples
let x = 5 in
x + let x = 4 in x + x;
val y = 2;
val y = 6;
var x : int;
begin
x := x + 2;
end;
address of x
cs7120 (Prasad)
x := x + 1;
value stored in location for x
L1-FP-HOF
13
(x=2) /\ (x+y>2)
(2+y>2)
vs
fun f (x : int) : int ;
begin
y := y + 1;
return ( x + y)
end;
(y=0) /\ (z=0) /\ (f(y)=f(z))
=
false
(y=0) /\ (z=0) /\ (f(z)=f(z))
=/= (y=0) /\ (z=0) /\ (f(z)=1)
cs7120 (Prasad)
L1-FP-HOF
14
• 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.
cs7120 (Prasad)
L1-FP-HOF
15
By GUY STEELE
Strict vs Non-strict
• A function is strict if it returns welldefined 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.
cs7120 (Prasad)
L1-FP-HOF
17
Traditional 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.
cs7120 (Prasad)
L1-FP-HOF
18
Global Summary
Programming Languages
Imperative
Functional
C, Pascal
Logic
Prolog
Dynamically Typed
(Meta-programming)
Statically Typed
(Type Inference/Reliable)
LISP, Scheme
Lazy Eval /
Pure
Haskell
cs7120 (Prasad)
L1-FP-HOF
Eager Eval
/ Impure
SML
19
Higher-Order Functions
cs7120 (Prasad)
L1-FP-HOF
20
Higher-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.
cs7120 (Prasad)
L1-FP-HOF
21
Nested Functional + Static Scoping
fun f x =
let
val g = fn y => 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)
cs7120 (Prasad)
L1-FP-HOF
22
ML function definitions
fun
|
elem_to_list []
= []
elem_to_list (h::t) =
[h] :: (elem_to_list t)
elem_to_list [“a”] = [[“a”]]
fun inc_each_elem []
= []
| inc_each_elem (h::t)=
(h+1) :: (inc_each_elem t)
inc_each_elem [1,2,3] = [2,3,4]
cs7120 (Prasad)
L1-FP-HOF
23
Abstracting Patterns of Recursion
fun
|
map
map
f
[]
= []
f (h::t) =
(f h)::(map f t)
fun
elem_to_list x =
map (fn x => [x]) x
val
inc_each_elem
=
map (fn x => x+1)
cs7120 (Prasad)
L1-FP-HOF
24
Functionals : 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
...
cs7120 (Prasad)
L1-FP-HOF
25
Orthogonality
• 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:
cs7120 (Prasad)
CommonLISP vs Scheme
L1-FP-HOF
26
Currying
fun
fun
plus (x, y)
add
x y
=
=
x + y
x + y
plus (5,3) = 8
add 5 3
= 8
add 5
= (fn x => 5+x)
• Curried functions are higher-order functions
that consume their arguments lazily.
• All ML functions are curried !
cs7120 (Prasad)
L1-FP-HOF
27
Significance 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.
cs7120 (Prasad)
L1-FP-HOF
28
fun curry f =
fn x => (fn y => f(x,y))
fun uncurry f =
fn (x,y) => (f x y)
curry (uncurry
f)
uncurry (curry f)
=
=
f
f
(Higher-order functions)
cs7120 (Prasad)
L1-FP-HOF
29
Classification of functions
• Primitive
+ , * , - , etc.
• Higher-order
– Hierarchical
(sort order list),(filter pred list)
– Self-applicable
map , id
fun
cs7120 (Prasad)
(E.g.,
double
f
=
L1-FP-HOF
(map (map f))
)
f o f;
composition
30
From Spec. to Impl.
• Spec:
(sqrt x) >= 0 /\ (sqrt x)^2 = x
• Computable Spec:
(sqrt x) >= 0 /\
abs((sqrt x)^2 - x) < eps
• Improving Approximations (Newton’s method):
y(n+1) = (y(n) + [x / y(n)]) / 2
cs7120 (Prasad)
L1-FP-HOF
31
fun improve x y =
( y + x / y) / 2.0 ;
val eps = 1.0e~5;
fun satis x y =
abs( y*y - x)
< 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;
cs7120 (Prasad)
L1-FP-HOF
32
ML : 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.
cs7120 (Prasad)
L1-FP-HOF
33
•
•
•
•
•
•
•
•
•
•
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
cs7120 (Prasad)
L1-FP-HOF
34
fun len []
| len (x::xs)
1 +
=
0
=
len xs
(define (len xs)
(if (null? xs)
0
(+ 1 (len (cdr xs)))
)
)
cs7120 (Prasad)
L1-FP-HOF
35