Download presentation
Presentation is loading. Please wait.
1
CS314 – Section 5 Recitation 10
Long Zhao Functional Programming (Scheme) Recursion & Higher Order Functions Slides available at
2
Scheme (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
3
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!”)
4
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 = ( )
5
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 <name> ( lambda ( <arguments> ) ( <function-body> ) )) (define abs (lambda (x) (if (< x 0) (- 0 x) x)))
6
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 (equal? 5 ‘(5)) ; gives #f (append ‘(1 3 5) evens) ; gives ( ) (cons ‘(1 3 5) evens) ; gives ((1 3 5) ) Are the last two lists same or different?
7
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)
8
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?
9
Key Features of Scheme Scoping: static Typing: dynamic
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 and garbage collection
10
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.
11
Iterative Functions 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! Scheme’s version of Iterative? Recursion
12
Recursive Problems 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 1! = 1 2! = 2 * 1 3! = 3 * 2 * 1 n! = n * (n-1) * (n-2) * … * 2 * 1
13
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
14
Factorial in Scheme Review: If - used to break code into cases
(define factorial (lambda (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.
15
Example of Factorial (define factorial (lambda (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
16
Example: Fibonacci (define fib (lambda (n) (cond ((= n 1) 1) <- base case ((= n 2) 1) <- 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))
17
Recursion (Exercise) Write following functions using recursion:
A function that summarizes numbers in a list. A function that takes a list (ls) and an object (x) and returns the first position of x in ls. The position is counted from 0. If x is not found in ls, the function returns #f.
18
Recursion (Exercise) A function that summarizes numbers in a list. ; 1
(define my-sum (lambda (ls) (if (null? ls) (+ (car ls) (my-sum (cdr ls))))))
19
Recursion (Exercise) A function that takes a list (ls) and an object (x) and returns the first position of x in ls. The position is counted from 0. If x is not found in ls, the function returns #f. ; 2 (define position (lambda (x ls) (position-helper x ls 0))) (define position-helper (lambda (x ls i) (cond ((null? ls) #f) ((eqv? x (car ls)) i) (else (position-helper x (cdr ls) (1 + i))))))
20
Higher Order Functions
Higher order functions are functions that takes functions as arguments. They are used for mapping, filtering, folding, and sorting of lists. The higher order functions promote modularity of programs. Writing higher order functions that are applicable in many cases makes program readable rather than writing recursive functions for individual cases.
21
(map procedure list1 list2 ...)
Mapping is a procedure that treats all list items in a same manner. The format is like as follows: Example: (map procedure list1 list2 ...) ; Adding each item of '(1 2 3) and '(4 5 6). (map + '(1 2 3) '(4 5 6)) ⇒ (5 7 9) ; Squaring each item of '(1 2 3) (map (lambda (x) (* x x)) '(1 2 3)) ⇒ (1 4 9)
22
(reduce procedure id list)
Higher order function that takes a binary, associative operation and uses it to “roll-up” a list. The format is like as follows: Example: (reduce procedure id list) (reduce + 0 '( )) ⇒ 10 (reduce + 0 '(1 2)) ⇒ 3 (reduce + 0 '(1)) ⇒ 1 (reduce + 0 '()) ⇒ 0
23
Map & Reduce (Exercise)
Write followings using map: A function that makes it twice that each item of a list of numbers. A function that subtracts items of two lists. Write a function that squares each item of a list, then sums them and then makes square root of it.
24
Map & Reduce (Exercise)
Write followings using map: A function that makes it twice that each item of a list of numbers. A function that subtracts items of two lists. ; 1 (define double (lambda (ls) (map (lambda (x) (* x 2)) ls))) ; 2 (define sub (lambda (ls1 ls2) (map - ls1 ls2)) )
25
Map & Reduce (Exercise)
Write a function that squares each item of a list, then sums them and then makes square root of it. (define sqrt-sum-sq (lambda (ls) (sqrt (reduce + 0 (map (lambda (x) (* x x)) ls)))))
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.