Presentation is loading. Please wait.

Presentation is loading. Please wait.

Cs7120 (Prasad)L1-FP-HOF1 Functional Programming Basics Correctness > Clarity > Efficiency.

Similar presentations


Presentation on theme: "Cs7120 (Prasad)L1-FP-HOF1 Functional Programming Basics Correctness > Clarity > Efficiency."— Presentation transcript:

1 cs7120 (Prasad)L1-FP-HOF1 Functional Programming Basics Correctness > Clarity > Efficiency

2 cs7120 (Prasad)L1-FP-HOF2 Function Definition Equations ; Recursion Higher-order functions Function Application Computation by expression evaluation Choices : parameter passing  Reliability  Types  Strong typing, Polymorphism, ADTs.  Garbage Collection

3 cs7120 (Prasad)L1-FP-HOF3 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.

4 cs7120 (Prasad)L1-FP-HOF4 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;

5 cs7120 (Prasad)L1-FP-HOF5 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; n := pm end; return n end;

6 cs7120 (Prasad)L1-FP-HOF6 Pitfalls : Sequencing (define (factorial n) (define (iter prod counter) (if (> counter n) prod (iter (* counter prod) (+ counter 1) ) )) (iter 1 1) )

7 cs7120 (Prasad)L1-FP-HOF7 (define (factorial n) (let ((prod 1)(counter 1)) (define (iter) (if (> counter n) prod (begin (set! prod (* counter prod)) (set! counter (+ 1 counter)) (iter)) ))

8 cs7120 (Prasad)L1-FP-HOF8 Function f A BA  B A BA 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.

9 cs7120 (Prasad)L1-FP-HOF9 Representation 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)

10 cs7120 (Prasad)L1-FP-HOF10 Expression Evaluation : Reduction fun double x = x + x; double ( 3 * 2) double(6) (3*2) + (3*2) (3*2) + o 6 + 6 6 + (3 * 2) 6 + o Applicative-Order Normal-Order Lazy (call by value) (call by name) (call by need)

11 cs7120 (Prasad)L1-FP-HOF11 Role 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.

12 cs7120 (Prasad)L1-FP-HOF12 Referential 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.

13 cs7120 (Prasad)L1-FP-HOF13 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 Examples

14 cs7120 (Prasad)L1-FP-HOF14 (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)

15 cs7120 (Prasad)L1-FP-HOF15 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.

16 By GUY STEELE

17 cs7120 (Prasad)L1-FP-HOF17 Strict vs Non-strict strictA 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.

18 cs7120 (Prasad)L1-FP-HOF18 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.

19 cs7120 (Prasad)L1-FP-HOF19 Global Summary Programming Languages ImperativeFunctionalLogic Dynamically Typed (Meta-programming) Statically Typed (Type Inference/Reliable) Lazy Eval / Pure Eager Eval / Impure C, PascalProlog LISP, Scheme HaskellSML

20 cs7120 (Prasad)L1-FP-HOF20 Higher-Order Functions

21 cs7120 (Prasad)L1-FP-HOF21 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.

22 cs7120 (Prasad)L1-FP-HOF22 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 )

23 cs7120 (Prasad)L1-FP-HOF23 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]

24 cs7120 (Prasad)L1-FP-HOF24 Abstracting Patterns of Recursion fun map f [] = [] | map 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)

25 cs7120 (Prasad)L1-FP-HOF25 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...

26 cs7120 (Prasad)L1-FP-HOF26 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 : CommonLISP vs Scheme

27 cs7120 (Prasad)L1-FP-HOF27 Currying fun plus (x, y) = x + y fun add 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. curriedAll ML functions are curried !

28 cs7120 (Prasad)L1-FP-HOF28 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. unaryAll ML functions are unary.

29 cs7120 (Prasad)L1-FP-HOF29 fun curry f = fn x => (fn y => f(x,y)) fun uncurry f = fn (x,y) => (f x y) curry (uncurry f) = f uncurry (curry f) = f (Higher-order functions)

30 cs7120 (Prasad)L1-FP-HOF30 Classification 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

31 cs7120 (Prasad)L1-FP-HOF31 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

32 cs7120 (Prasad)L1-FP-HOF32 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;

33 cs7120 (Prasad)L1-FP-HOF33 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.

34 cs7120 (Prasad)L1-FP-HOF34 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 cs7120 (Prasad)L1-FP-HOF35 fun len [] = 0 | len (x::xs) = 1 + len xs (define (len xs) (if (null? xs) 0 (+ 1 (len (cdr xs))) )


Download ppt "Cs7120 (Prasad)L1-FP-HOF1 Functional Programming Basics Correctness > Clarity > Efficiency."

Similar presentations


Ads by Google