Presentation is loading. Please wait.

Presentation is loading. Please wait.

Procedural vs Functional Style

Similar presentations


Presentation on theme: "Procedural vs Functional Style"— Presentation transcript:

1 Procedural vs Functional Style
procedural = imperative cs3180(Prasad) L13FP

2 Abstracting Expressions
Scale a 2D-point p by a factor c (define scale (lambda (c p) (list (* c (first p)) (* c (second p)) ) )) Can abbreviate a fixed and finite number of function applications for readability, modifiability, and reusability. (* 2 x ) (+ x x) (ROL x) = DOUBLE cs3180(Prasad) L13FP

3 Procedural/Imperative vs Functional
Program: a sequence of instructions for a von Neumann m/c. Computation by instruction execution. Repetition: Iteration. Modifiable or updateable variables. Program: a collection of function definitions (m/c independent). Computation by term rewriting. Repetition: Recursion. “Assign-only-once” variables. cs3180(Prasad) L13FP

4 Functional Style : Illustration
Definition : Equations sum(0) = 0 sum(n) = n + sum(n-1) Computation : Substitution and Replacement sum(2) = sum (2-1) = … = 3 cs3180(Prasad) L13FP

5 Paradigm vs Language Procedural Style Functional Style
i := 0; sum := 0; while (i < n) do begin i := i + 1; sum := sum + i end; Storage efficient Functional Style func sum(i:int) : int; begin if i = 0 then 0 else i + sum(i-1) end; No Side-effect Recursive call requires allocation of fresh storage for formal arguments (and local variables). This is because after the recursion returns we still have use for the old value of n. (cf. tail -recursion) cs3180(Prasad) L13FP

6 Role of Variables Imperative (read/write) i 0 1 2 3 ...
sum Functional (read only) i sum1 i sum2 i sum3 3 6 2 3 Storage reused vs memory freshly allocated each time a call is made 1 1 cs3180(Prasad) L13FP

7 Bridging the Gap A tail recursive definition can be automatically optimized for space by translating it into an equivalent while-loop. func sum(i : int, r : int) : int; begin if i = 0 then r else sum(i-1, i+r) end So, Scheme does not have loop-constructs. In a tail call, the result of the recursive call is the same as the result returned for the original call. So there is no processing of the recursive call result, and there is no need to retain the old values of the formals. In other words, formals can be destructively assigned to. Recursion is strictly more “expressive” than iteration but in cases where recursion can be cast as an iteration for efficiency, Scheme mandates that the interpreters do so. cs3180(Prasad) L13FP

8 Iteration vs Recursion
Recursion = Iteration + Stack Iteration = Tail Recursion cs3180(Prasad) L13FP


Download ppt "Procedural vs Functional Style"

Similar presentations


Ads by Google