Recitation 10 Long Zhao lz311rutgersedu Functional Programming Scheme Recursion amp Higher Order Functions Slides available at httpwwwilabrutgersedulz311CS314 slide 2 Scheme Expressions and Lists ID: 614129
Download Presentation The PPT/PDF document "CS314 – Section 5" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
CS314 – Section 5Recitation 10
Long Zhao (lz311@rutgers.edu)Functional Programming (Scheme)Recursion & Higher Order Functions
Slides available at http://www.ilab.rutgers.edu/~lz311/CS314Slide2
slide
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 parenthesesFor example, (0 2 4 6 8) is a list of even numbersThe empty list is written ()Lists represent both functions and dataSlide3
slide
3
Elementary Values
Numbers
Integers, floats, rationals
SymbolsInclude special Boolean symbols #t and #f CharactersFunctionsStrings“Hello, world”Predicate names end with ?(symbol? ‘(1 2 3)), (list? (1 2 3)), (string? “Yo!”)Slide4
slide
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 (+ 1 2 3 4 5)) ; sum = (+ 1 2 3 4 5)Slide5
slide
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)))Slide6
slide
6
Operations on Lists
car,
cdr
, cons(define evens ‘(0 2 4 6 8)) (car evens) ; gives 0(cdr evens) ; gives (2 4 6 8)(cons 1 (cdr evens)) ; gives (1 2 4 6 8)Other operations on lists(null? ‘()) ; gives #t
(equal? 5 ‘(5)) ; gives #f
(append ‘(1 3 5) evens) ; gives (1 3 5 0 2 4 6 8)
(cons ‘(1 3 5) evens) ; gives ((1 3 5) 0 2 4 6 8)
Are the last two lists same or different?Slide7
slide
7
Conditionals
General form
(cond (p1 e1) (p2 e2) … (pN eN))Evaluate pi in order; each pi evaluates to #t or #fValue = value of ei for the first pi that evaluates to #t or eN if pN
is “else” and all p
1
… p
N-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)Slide8
slide
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?Slide9
slide
9
Key Features of Scheme
Scoping: static
Typing: dynamic
No distinction between code and dataBoth functions and data are represented as listsLists are first-class objectsCan be created dynamically, passed as arguments to functions, returned as results of functions and expressionsThis requires heap allocation and garbage collectionSlide10
Recursion
(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. Slide11
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?
RecursionSlide12
Recursive Problems
A problem that can be reduced to a simpler version of itself plus some simple operationsWhen 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 * 1Slide13
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 directlySlide14
Factorial in Scheme
(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.Slide15
Example of Factorial
(define factorial
(lambda (x
) (if (= x 1) 1 (* x (factorial (- x 1))))))
(factorial 4):
(* 4 (* 3 (factorial 2)))
(* 4 (* 3 (* 2 (factorial 1))))
(* 4 (* 3 (* 2 1)))
(* 4 (* 3 2))
(* 4 6)
24
(* 4 (factorial 3))Slide16
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))Slide17
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.Slide18
Recursion (Exercise)
A function that summarizes numbers in a list.
; 1
(define my-sum
(lambda (ls)
(if (null? ls)
0
(+ (car ls) (my-sum (
cdr
ls))))))
Slide19
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
)))))) Slide20
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.Slide21
Map
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)
Slide22
Reduce
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 + 0 '(1 2 3 4)) ⇒ 10
(reduce + 0 '(1 2)) ⇒ 3
(reduce + 0 '(1)) ⇒ 1
(reduce + 0 '()) ⇒ 0
(reduce
procedure
id
list
)
Slide23
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.Slide24
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))
)Slide25
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)))))