Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS314 – Section 5 Recitation 9

Similar presentations


Presentation on theme: "CS314 – Section 5 Recitation 9"— Presentation transcript:

1 CS314 – Section 5 Recitation 9
Long Zhao Parameter Passing Style Functional Programming (Scheme) Slides available at

2 Parameter Passing By value By reference By value-result By result
By name

3 Pass by Value Caller passes r-value of the argument to function
Compute the value of the argument at the time of the call and assign that value to the parameter Reduces “aliasing” Aliasing: two names refer to the same memory location Function cannot change value of caller’s variable All arguments in C and Java (basic type) are passed by value To allow caller’s variables to be modified, pointers can be passed as arguments in C Example: void swap(int *a, int *b) { … }

4 Pass by Reference Caller passes l-value of the argument to function
int h, i; void B(int* w) { int j, k; i = 2*(*w); *w = *w+1; } void A(int* x, int* y) { bool i, j; B(&h); int main() { int a, b; h = 5; a = 3; b = 2; A(&a, &b); Caller passes l-value of the argument to function Compute the address of the argument and assign that address to the parameter Increases aliasing Function can modify caller’s variable via the address it received as argument

5 Pass by Value-Result Pass by value at the time of the call and/or copy the result back to the argument at the end of the call (copy-in-copy-out) Reference and value-result are the same, except when aliasing occurs Same variable is passed for two different parameters Same variable is both passed and globally referenced from the called function

6 Pass by Result The formal parameter acts as an uninitialized local variable within the called procedure. The parameter is then assigned a value during execution. This value is then “passed back” and assigned to the actual parameter.

7 Example (Pass by Value & Reference)
What is output when function Print is called? (pass by value or reference)

8 Example (Pass by Result)
c : array[1…10] of integer; m, n: integer; procedure r(i, j : integer) begin i := 0; j := 0; i := i + 1; j := j + 2; end r; m := 2; n := 3; r(m , n); write m, n; // 1, 2

9 Example (Pass by Value Result)
int x = 1; // global x Void func1(int a) { print(a); print(x); a = 3; x = 4; } Void main() { func1(x); // 1 // 3 // 4

10 Parameter Passing (Exercise)
1. 2. function joe(int a, int b, int c)   begin     a := b + c;     b := c + 1;     print a, b, c;   end function main   begin     int i := 5;     int j := 10;     ink k := 15;     joe(i, j, j + k);     print i, j, k;   end function phil(int a, int b, int c)   begin     b := b + 5;     b := a + c + 4;     print a, b, c;   end function main   begin     int j := 10;     ink k := 15;     phil(j, j, j + k);     print j, k;   end All parameters are passed by value? Pass a and b by value-result, and c by value? Pass a and b by reference, and c by value? Pass a and b by value-result, and c by value?

11 Parameter Passing (Exercise)
1. function joe(int a, int b, int c)   begin     a := b + c;     b := c + 1;     print a, b, c;   end function main   begin     int i := 5;     int j := 10;     ink k := 15;     joe(i, j, j + k);     print i, j, k;   end All parameters are passed by value? Pass a and b by value-result, and c by value?

12 Parameter Passing (Exercise)
2. function phil(int a, int b, int c)   begin     b := b + 5;     b := a + c + 4;     print a, b, c;   end function main   begin     int j := 10;     ink k := 15;     phil(j, j, j + k);     print j, k;   end Pass a and b by reference, and c by value? Pass a and b by value-result, and c by value?

13 Scheme Impure functional language Key idea: symbolic programming using
list expressions and recursive functions Garbage-collected, heap-allocated (we’ll see why) Lexical scoping, block structure Some imperative features

14 Expressions and Lists Cambridge prefix notation: (f x1 x2 … xn)
(+ 2 2) (+ (* 5 4) (- 6 2)) means 5*4 + (6-2) List = series of expressions enclosed in parentheses For example, ( ) is a list of even numbers The empty list is written () Lists represent both functions and data

15 Elementary Values Numbers Symbols Characters Functions Strings
Integers, floats, rationals Symbols Include special Boolean symbols #t and #f Characters Functions Strings “Hello, world” Predicate names end with ? (symbol? ‘(1 2 3)), (list? (1 2 3)), (string? “Yo!”)

16 Top-Level Bindings define establishes a mapping from a symbolic name to a value in the current scope Think of a binding as a table: symbol  value (define size 2) ; size = 2 (define sum ( )) ; sum = ( )

17 Functions ( define ( name arguments ) ( function-body ) )
(define (factorial n) (if (< n 1) 1 (* n (factorial (- n 1))))) (define (square x) (* x x)) (define (sumsquares x y) (+ (square x) (square y))) (define abs (lambda (x) (if (< x 0) (- 0 x) x))) Arguments are passed by value Eager evaluation: argument expressions are always evaluated, even if the function never uses them Alternative: lazy evaluation (e.g., in Haskell)

18 Expression Evaluation
Read-eval-print loop Names are replaced by their current bindings x ; evaluates to 5 Lists are evaluated as function calls (+ (* x 4) (- 6 2)) ; evaluates to 24 Constants evaluate to themselves. ‘red ; evaluates to ‘red Innermost expressions are evaluated first (define (square x) (* x x)) (square (+ 1 2))  (square 3)  (* 3 3)  9

19 Operations on Lists car, cdr, cons Other operations on lists
(define evens ‘( )) (car evens) ; gives 0 (cdr evens) ; gives ( ) (cons 1 (cdr evens)) ; gives ( ) Other operations on lists (null? ‘()) ; gives #t, or true (equal? 5 ‘(5)) ; gives #f, or false (append ‘(1 3 5) evens) ; gives ( ) (cons ‘(1 3 5) evens) ; gives ((1 3 5) ) Are the last two lists same or different?

20 Conditionals General form (cond (p1 e1) (p2 e2) … (pN eN))
Evaluate pi in order; each pi evaluates to #t or #f Value = value of ei for the first pi that evaluates to #t or eN if pN is “else” and all p1 … pN-1 evaluate to #f Simplified form (if (< x 0) (- 0 x)) ; if-then (if (< x y) x y) ; if-then-else Boolean predicates: (and (e1) … (eN)), (or (e1) … (eN)), (not e)

21 Other Control Flow Constructs
Case selection (case month ((sep apr jun nov) 30) ((feb) 28) (else 31) ) What about loops? Iteration  Tail recursion Scheme implementations must implement tail-recursive functions as iteration

22 Imperative Features Scheme allows imperative changes to values of variable bindings (define x `(1 2 3)) (set! x 5) Is it Ok for new value to be of a different type? Why? What happens to the old value?

23 Key Features of Scheme Scoping: static
Typing: dynamic (what does this mean?) No distinction between code and data Both functions and data are represented as lists Lists are first-class objects Can be created dynamically, passed as arguments to functions, returned as results of functions and expressions This requires heap allocation (why?) and garbage collection (why?) Self-evolving programs

24 Recursion (print “What is the story? It is: ”)
(define tell-story (lambda () (print ‘’Once upon a time there was a mountain. ‘’) (print ‘’On the mountain, there was a temple. ‘’) (print ‘’In the temple, there was an old monk telling a story. ‘’) (print “What is the story? It is: ”) (tell-story)) Definition: A recursive procedure is a procedure that calls itself.

25 Iterative Functions The problem with recursive processes: deferred operations takes up space. An iterative procedure uses constant space. A “true” iterative procedure has no self-calls. public int factorial(int n) { int answer = 1; for (int i = 1; i <=n; i++) { answer *= n; } return answer; NOTE: This example is written in Java, not Scheme!

26 Scheme’s version of Iterative
Tail Recursion- recursion with no deferred operations. (tell-story) is actually an example of tail recursion. Has counter and keeps track of current answer.

27 Recursive Problems 0! = 1 1! = 1 2! = 2 * 1 3! = 3 * 2 * 1
A problem that can be reduced to a simpler version of itself plus some simple operations When we’re solving a recursive problem, we want the function to stop somewhere-> Base Case Classic example: factorial 0! = 1 1! = 1 2! = 2 * 1 3! = 3 * 2 * 1 n! = n * (n-1) * (n-2) * … * 2 * 1

28 Factorial in Scheme Review: If - used to break code into cases
(define (factorial x) (if (= x 1) 1 (* x (factorial (- x 1))))) Review: If - used to break code into cases (if predicate consequent alternate) Predicate is the test. Consequent executes if predicate is true. Alternate executes if predicate is false.

29 Example of Factorial (define (factorial x) (if (= x 1) 1
(* x (factorial (- x 1))))) (factorial 4): (* 4 (factorial 3)) (* 4 (* 3 (factorial 2))) (* 4 (* 3 (* 2 (factorial 1)))) (* 4 (* 3 (* 2 1))) (* 4 (* 3 2)) (* 4 6) 24 Definition: A recursive process has deferred operations.

30 How to make recursive procedures:
We want to make a procedure that solves a problem with input size n 1. Pretend you known how to solve the problem for input sizes 1, 2,…, n-1 2. Use smaller instances and simple operations to formulate solution for input of size n 3. Identify base case and solve it directly

31 Example: Fibonacci (define (fib n) (cond ((= n 1) 1) <- base case ((= n 2) 2) <- base case (else (+ (fib (- n 1)) (fib (- n 2)))))) The cond structure: for when there are multiple cases. (cond ((predicate1) consequent1) ((predicate2) consequent2) (else alternate))

32 Tail Recursive Factorial
(define (factorial n) (fact-helper 1 1 n)) (define (fact-helper product counter n) (if (> counter n) product (fact-helper (* product counter) (+ counter 1) n))))

33 Iterative Factorial Example
(define (factorial n) (fact-helper 1 1 n)) (define (fact-helper product counter n) (if (> counter n) product (fact-helper (* product counter) (+ counter 1) n)))) Ex: (factorial 3) (fact-helper 1 1 3) (fact-helper 1 2 3) (fact-helper 2 3 3) (fact-helper 6 4 3) 6

34 Summary Recursion Iteration Tail Recursion
Used to solve problems that can be broken into smaller instances plus some simple operations A function keeps calling itself until some base case Problem: deferred operations take up space Iteration Uses a counter. Always keeps track of current “solution” No deferred operations. No self-calls Tail Recursion Scheme’s version of iterative Self-calls with no deferred operations


Download ppt "CS314 – Section 5 Recitation 9"

Similar presentations


Ads by Google