1 מבוא מורחב למדעי המחשב בשפת Scheme תרגול 11. 2 Outline Mutable list structure RPN calculator Vectors and sorting.

Slides:



Advertisements
Similar presentations
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 5. 2 List Utilities Scheme built-in procedures –(list x y z...) –(list-ref lst index) –(length lst) –(append.
Advertisements

1 Programming Languages (CS 550) Lecture Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
Functional Programming. Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends.
Chapter 3 Functional Programming. Outline Introduction to functional programming Scheme: an untyped functional programming language.
מבוא מורחב 1 Lecture #7. מבוא מורחב 2 The rational number abstraction Wishful thinking: (make-rat ) Creates a rational number (numer ) Returns the numerator.
מבוא מורחב - שיעור 91 Lecture 9 Lists continued: Map, Filter, Accumulate, Lists as interfaces.
Cs7100(Prasad)L11Clos1 Closures and Streams. Contemporary Interest in Closures The concept of closures was developed in the 1960s and was first fully.
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 11. Metacircular Evaluator 4.1, pages definitions file on web 2.
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 7 1. Outline More list examples Symbols 2.
מבוא מורחב - שיעור 15 1 Lecture 15 Streams. מבוא מורחב - שיעור 15 2 Streams: Motivation (define (sum-primes a b) (define (iter count accum) (cond ((>
6.001 SICP 1 Normal (Lazy) Order Evaluation Memoization Streams.
6.001 SICP SICP – October HOPs, Lists, Trees Trevor Darrell 32-D512 Office Hour: W web page:
Extended Introduction to CS Preparation for Final Exam.
Types of the past exam questions I. Write/Complete Code II. Evaluate Expressions III. Analyze Complexity IV. Meta-circular Evaluator.
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 11. Dotted tail notation (define (proc m1 m2. opt) ) Mandatory Arguments: m1, m2 Mandatory Arguments: m1, m2.
Extended Introduction to CS Preparation for Final Exam.
Chapter 15 Functional Programming Languages. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Introduction Design of imperative languages is.
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 13. Streams 3.5, pages definitions file on web 2.
SICP Data Mutation Primitive and Compound Data Mutators Stack Example non-mutating mutating Queue Example non-mutating mutating.
מבוא מורחב - שיעור 81 Lecture 8 Lists and list operations (continue).
SICP Infinite streams – using lazy evaluation Beyond Scheme – designing language variants: Streams – an alternative programming style!
( (lambda (z) (define x (lambda (x) (lambda (y z) (y x)))) ( ( (x (lambda () z)) (lambda (z) z) 3 ) ) ) 2)
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
מבוא מורחב 1 Lecture #8. מבוא מורחב 2 Shall we have some real fun.. Lets write a procedure scramble.. (scramble (list )) ==> ( ) (scramble.
1 (Functional (Programming (in (Scheme)))) Jianguo Lu.
Closures and Streams More on Evaluations CS784(pm)1.
1 Lecture OO, the notion of inheritance 3 Stacks in OO style (define (make-stack) (let ((top-ptr '())) (define (empty?) (null? top-ptr)) (define.
CS220 Programming Principles 프로그래밍의 이해 2002 가을학기 Class 13: Streams 한 태숙.
Functional Programming in Scheme and Lisp. Overview In a functional programming language, functions are first class objects. You can create them, put.
1 Lecture 16: Lists and vectors Binary search, Sorting.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 12. Outline Streams Infinite streams Stream implementation Questions from exams 2.
1 Append: process  (append list1 list2) (cons 1 (append ‘(2) list2)) (cons 1 (cons 2 (append ‘() list2))) (cons 1 (cons 2 list2)) (define (append list1.
6.001 Final Exam Review Spring 2005 By Gerald Dalley.
1 Programming Languages (CS 550) Lecture 4 Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
CS61A Lecture Colleen Lewis. Clicker poll Where do you think you’re learning the most? I assume you’ll learn the most in lab & disc (so.
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 6. 2 List Utilities Scheme built-in procedures –(list x y z...) –(list-ref lst index) –(length lst) –(append.
1 Vectors, binary search, and sorting. 2 We know about lists O(n) time to get the n-th item. Consecutive cons cell are not necessarily consecutive in.
Principles Of Programming Languages Lecture 2 Today Design-By-Contract Data Structures: Lists and Pairs Iteration vs. Recursion If we have time: live.
6.037 Lecture 7B Scheme Variants Normal Order Lazy Evaluation Streams Edited by Mike Phillips & Ben Vandiver Original Material by Eric Grimson & Duane.
CS314 – Section 5 Recitation 9
CS314 – Section 5 Recitation 10
Lecture 16 Streams continue Infinite Streams מבוא מורחב - שיעור 16.
6.001 SICP Variations on a Scheme
PPL Lecture Notes: Chapter 3 High-Order Procedures Revisited.
PPL Lazy Lists.
September 4, 1997 Programming Languages (CS 550) Lecture 6 Summary Operational Semantics of Scheme using Substitution Jeremy R. Johnson TexPoint fonts.
Lecture 14 - Environment Model (cont.) - Mutation - Stacks and Queues
Closures and Streams cs784(Prasad) L11Clos
COP4020 Programming Languages
Env. Model Implementation
6.001 SICP Data abstractions
Streams Sections 3.5.1,3.5.2 Pages
The Metacircular Evaluator
Lecture 18 Infinite Streams and
Lecture 18.
Lecture #8 מבוא מורחב.
The Metacircular Evaluator (Continued)
Explicit Application of Procedures, and Explicit Evaluation
Streams, Delayed Evaluation and a Normal Order Interpreter
Lecture 14 - Environment Model (cont.) - Mutation - Stacks and Queues
6.001 SICP Variations on a Scheme
Mutators for compound data Stack Queue
6.001 SICP Data Mutation Primitive and Compound Data Mutators
Announcements Quiz 5 HW6 due October 23
List and list operations (continue).
6.001 SICP Interpretation Parts of an interpreter
Lecture # , , , , מבוא מורחב.
Rehearsal: Lazy Evaluation Infinite Streams in our lazy evaluator
Presentation transcript:

1 מבוא מורחב למדעי המחשב בשפת Scheme תרגול 11

2 Outline Mutable list structure RPN calculator Vectors and sorting

3 (define (set-to-wow! x) (set-car! (car x) 'wow) x) (define x (list 'a 'b)) (define z1 (cons x x)) (set-to-wow! z1) ((wow b) wow b) eq? point to the same object, equal? same content (eq? (car z1) (cdr z1)) is true (eq? (car z2) (cdr z2)) is false (define z2 (cons (list 'a 'b) (list 'a 'b))) (set-to-wow! z2) ((wow b) a b)

4 Map without list copying (define (map! f s) (if (null? s) 'done (begin (set-car! s (f (car s))) (map! f (cdr s))))) (define s '( )) (map! square s) => done s => ( )

5 append! (define (append! x y) (set-cdr! (last-pair x) y) x) where: (define (last-pair x) (if (null? (cdr x)) x (last-pair (cdr x))))

6 append vs. append! (define x ‘(a b)) (define y ‘(c d)) (define z (append x y)) z ==> (a b c d) (cdr x) ==> ? (define w (append! x y)) w ==> (a b c d) (cdr x) ==> ?

7 (define (last-pair x) (if (null? (cdr x)) x (last-pair (cdr x)))) (define (make-cycle x) (set-cdr! (last-pair x) x) x) (define z (make-cycle (list 'a 'b 'c))) Cycle

8 What happens? (last-pair z) => a b c z

9 Examine the list and determine whether it contains a cycle, whether a program that tried to find the end of the list by taking successive cdr s would go into an infinite loop (define (is-cycle? c) (define (loop fast slow) (cond ((null? fast) #f) ((null? (cdr fast)) #f) ((eq? (cdr fast) slow) #t) (else (loop (cddr fast) (cdr slow))))) (loop c c)) is-cycle?

10 Bounded Counter A bounded counter can be incremented or decremented in steps of 1, until upper and lower bounds are reached. syntax: (make-bounded-counter init bottom top) example: (define c (make-bounded-counter 3 1 5)) (counter-inc! c)  4 (counter-inc! c)  5 (counter-dec! c)  4

11 List Implementation Constructor: (define (make-bounded-counter init bottom top) (list init bottom top)) Selectors: (define (counter-value c) (car c)) (define (counter-bottom c) (cadr c)) (define (counter-top c) (caddr c))

12 List Implementation – cont. Mutators: (define (counter-inc! c) (if (< (counter-value c) (counter-top c)) (set-car! c (+ 1 (counter-value c)))) (counter-value c)) (define (counter-dec! c) (if (> (counter-value c) (counter-bottom c)) (set-car! c (- (counter-value c) 1))) (counter-value c))

13 Polish Notation PostFix Notation: operands before operators Expressions with binary operators can be written without Parentheses Apply operators, from left to right, on the last two numbers – * + –5 3 2 * + –5 6 + – 11 Stack implementation: –Init: Empty stack –Number: insert! Into stack –Operator: apply on 2 top stack elements and insert! result into stack

14 Simulation (calc) TOP= 3 2 * TOP= 6 + TOP= 11 exit ok

15 Read & Eval (read) - returns an expression from the user (eval exp) - evaluates an expression We will use these functions in: –(perform m) - receives a symbol of an operation, applies it on the two top numbers in the stack, and returns the result to the stack –(iter) - reads an input from the user. If it is a number it is pushed to the stack, if it is an operator we call perform

16 perform (define (perform m) (let ((arg2 ((stk 'top)))) ((stk 'delete!)) (let ((arg1 ((stk 'top)))) ((stk 'delete!)) ((stk 'insert!) ((eval m) arg1 arg2)))))

17 iter (define (iter) (let ((in (read))) (if (eq? in 'exit) 'ok (begin (cond ((number? in) ((stk 'insert!) in)) (else (perform in) (display "TOP= ") (display ((stk 'top))) (newline))) (iter)))))

18 Calc (define (calc) (let ((stk (make-stack))) (define (perform m)...) (define (iter)... ) (iter)))

19 Vectors Constructors: (vector v1 v2 v3...) (make-vector size init) Selector: (vector-ref vec place) Mutator: (vector-set! vec place value) Other functions: (vector-length vec)

20 Example - accumulating (define (accumulate-vec op base vec) (define (helper from to) (if (> from to) base (op (vector-ref vec from) (helper (+ from 1) to)))) (helper 0 (- (vector-length vec) 1)))

21 Bucket Sort Problem: Sorting numbers that distribute “uniformly” across a given interval (for example, [0,1) ). Observation: The number of elements that fall within a sub-interval is proportional to the sub-interval’s size Idea: –Divide into sub-intervals (buckets) –Throw each number into appropriate bucket –Sort within each bucket (any sorting method) –Adjoin all sorted buckets

22 Example If we want ~3 numbers in each bucket, we need 3-4 buckets. Using 3 buckets we have: Bucket : Bucket – 0.667: Bucket – 1 : Sorting: Now sort! Bucket : Bucket – 0.667: Bucket – 1 :

23 Analysis Observation: If number of buckets is proportional to the number of elements, then the number of elements in each bucket is more or less the same, and bounded by a constant. Dividing into buckets: O(n) Sorting one bucket: O(1) Sorting all buckets: O(n) Adjoining sorted sequences: O(n)

24 Implementation A bucket is a list The set of buckets is a vector The elements are sorted while inserted into the buckets (very similar so insertion sort): (define (insert x s) (cond ((null? s) (list x)) ((< x (car s)) (cons x s)) (else (cons (car s) (insert x (cdr s))))))

25 Implementation – for-each Scheme primitive Similar to map, without returning a value Useful for side-effects (define (for-each proc lst) (if (null? lst) ‘done (begin (proc (car lst)) (for-each proc (cdr lst)))))

26 Implementation – cont. (define (bucket-sort s) (let* ((size 5) (n (ceiling (/ (length s) size))) (buckets (make-vector n null))) (define (insert! x) (let ((bucket (inexact->exact (floor (* n x))))) (vector-set! buckets bucket (insert x (vector-ref buckets bucket))))) (for-each insert! s) (accumulate-vec append null buckets)))

Streams 3.5, pages definitions file on web 27

cons, car, cdr (define s (cons 9 (begin (display 7) 5))) -> prints 7 The display command is evaluated while evaluating the cons. (car s) -> 9 (cdr s) -> 5 28

cons-stream, stream-car, stream-cdr (define s (cons-stream 9 (begin (display 7) 5))) Due to the delay of the second argument, cons-stream does not activate the display command (stream-car s) -> 9 (stream-cdr s) -> prints 7 and returns 5 stream-cdr activates the display which prints 7, and then returns 5. 29

List enumerate (define (enumerate-interval low high) (if (> low high) nil (cons low (enumerate-interval (+ low 1) high)))) (enumerate-interval 2 8) -> ( ) (car (enumerate-interval 2 8)) -> 2 (cdr (enumerate-interval 2 8)) -> ( ) 30

Stream enumerate (define (stream-enumerate-interval low high) (if (> low high) the-empty-stream (cons-stream low (stream-enumerate-interval (+ low 1) high)))) (stream-enumerate-interval 2 8) -> (2. # ) (stream-car (stream-enumerate-interval 2 8)) -> 2 (stream-cdr (stream-enumerate-interval 2 8)) -> (3. # ) 31

List map (map ) (define (map proc s) (if (null? s) nil (cons (proc (car s)) (map proc (cdr s))))) (map square (enumerate-interval 2 8)) -> ( ) 32

Stream map (map ) (define (stream-map proc s) (if (stream-null? s) the-empty-stream (cons-stream (proc (stream-car s)) (stream-map proc (stream-cdr s)) ))) (stream-map square (stream-enumerate-interval 2 8)) -> (4. # ) 33

List of squares (define squares (map square (enumerate-interval 2 8))) squares -> ( ) (car squares) -> 4 (cdr squares) -> ( ) 34

Stream of squares (define stream-squares (stream-map square (stream-enumerate-interval 2 8))) stream-squares -> (4. # ) (stream-car stream-squares) -> 4 (stream-cdr stream-squares) -> (9. # ) 35

List reference (define (list-ref s n) (if (= n 0) (car s) (list-ref (cdr s) (- n 1)))) (define squares (map square (enumerate-interval 2 8))) (list-ref squares 3) -> 25 36

Stream reference (define (stream-ref s n) (if (= n 0) (stream-car s) (stream-ref (stream-cdr s) (- n 1)))) (define stream-squares (stream-map square (stream-enumerate-interval 2 8))) (stream-ref stream-squares 3) -> 25 37

List filter (filter ) (define (filter pred s) (cond ((null? s) nil) ((pred (car s)) (cons (car s) (filter pred (cdr s)))) (else (filter pred (cdr s))))) (filter even? (enumerate-interval 1 20)) -> ( ) 38

Stream filter (stream-filter ) (define (stream-filter pred s) (cond ((stream-null? s) the-empty-stream) ((pred (stream-car s)) (cons-stream (stream-car s) (stream-filter pred (stream-cdr s)))) (else (stream-filter pred (stream-cdr s))) ))) (stream-filter even? (stream-enumerate-interval 1 20)) -> (2. # ) 39

Generalized list map (generalized-map … ) (define (generalized-map proc. arglists) (if (null? (car arglists)) nil (cons (apply proc (map car arglists)) (apply generalized-map (cons proc (map cdr arglists)))))) (generalized-map + squares squares squares) -> ( ) 40

Generalized stream map (generalized-stream-map … ) (define (generalized-stream-map proc. argstreams) (if (stream-null? (car argstreams)) the-empty-stream (cons-stream (apply proc (map stream-car argstreams)) (apply generalized-stream-map (cons proc (map stream-cdr argstreams)))))) (generalized-stream-map + stream-squares stream-squares stream-squares) -> (12. # ) 41

List for each (define (for-each proc s) (if (null? s) 'done (begin (proc (car s)) (for-each proc (cdr s))))) 42

Stream for each (define (stream-for-each proc s) (if (stream-null? s) 'done (begin (proc (stream-car s)) (stream-for-each proc (stream-cdr s))))) useful for viewing (finite!) streams (define (display-stream s) (stream-for-each display s)) (display-stream (stream-enumerate-interval 1 20)) -> prints 1 … 20 done 43

Lists (define sum 0) (define (acc x) (set! sum (+ x sum)) sum) (define s (map acc (enumerate-interval 1 20))) s -> ( ) sum -> 210 (define y (filter even? s)) y -> ( ) sum -> 210 (define z (filter (lambda (x) (= (remainder x 5) 0)) s)) z -> ( ) sum ->

(list-ref y 7) -> 136 sum -> 210 (display z) -> prints ( ) sum ->

Streams (define sum 0) (define (acc x) (set! sum (+ x sum)) sum) (define s (stream-map acc (stream-enumerate-interval 1 20))) s -> (1. # )sum -> 1 (define y (stream-filter even? s)) y -> (6. # )sum -> 6 (define z (stream-filter (lambda (x) (= (remainder x 5) 0)) s)) z -> (10. # )sum -> 10 46

(stream-ref y 7) -> 136 sum -> 136 (display-stream z) -> prints done sum ->

Defining streams implicitly by delayed evaluation Suppose we needed an infinite list of Dollars. We can (define bill-gates (cons-stream ‘dollar bill-gates)) If we need a Dollar we can take the car (stream-car bill-gates) -> dollar The cdr would still be an infinite list of Dollars. (stream-cdr bill-gates)->(dollar. # ) 48

49 Infinite Streams Formulate rules defining infinite series wishful thinking is key 49

1,ones (define ones (cons-stream 1 ones)) 1,1,1,… = ones = 50

2,twos (define twos (cons-stream 2 twos)) ones + ones adding two infinite series of ones (define twos (stream-map + ones ones)) 2 * ones element-wise operations on an infinite series of ones (define twos (stream-map (lambda (x) (* 2 x)) ones)) or (+ x x) 2,2,2,… = twos = 51

1,2,3,… = integers = 1,ones + integers 1,1,1… 1,2,3,… 2,3,4,… (define integers (cons-stream 1 (stream-map + ones integers))) + 52

0,1,1,2,3,… = fibs = 0,1,fibs + (fibs from 2 nd position) 0,1,1,2,… 1,1,2,3,… 1,2,3,5,… (define fibs (cons-stream 0 (cons-stream 1 (stream-map + fibs (stream-cdr fibs))))) + 53

1,doubles + doubles 1,2,4,8,… 2,4,8,16,… (define doubles (cons-stream 1 (stream-map + doubles doubles))) 1,2,4,8,… = doubles = + 54

1,2 * doubles (define doubles (cons-stream 1 (stream-map (lambda (x) (* 2 x)) doubles))) or (+ x x) 1,2,4,8,… = doubles = 55

1,factorials * integers from 2 nd position 1, 1*2, 1*2*3,… 2, 3, 4,… 1*2,1*2*3,1*2*3*4,… (define factorials (cons-stream 1 (stream-map * factorials (stream-cdr integers)))) 1,1x2,1x2x3,... = factorials = x 56

(1),(1 2),(1 2 3),… = runs = (1), append runs with a list of integers from 2 nd position (1), (1 2), (1 2 3),… (2), (3), (4),… (1 2),(1 2 3),( ),… (define runs (cons-stream (list 1) (stream-map append runs (stream-map list (stream-cdr integers))))) append 57

a0,a0+a1,a0+a1+a2,… = partial sums = a0,partial sums + (stream from 2 nd pos) a0, a0+a1, a0+a1+a2,… a1, a2, a3,… a0+a1,a0+a1+a2,a0+a1+a2+a3,… (define (partial-sums a) (cons-stream (stream-car a) (stream-map + (partial-sums a) (stream-cdr a)))) + 58

59 Partial Sums (cont.) (define (partial-sums a) (define sums (cons-stream (stream-car a) (stream-map + sums (stream-cdr a)))) sums) This implementation is more efficient since it uses the stream itself rather than recreating it recursively 59

Repeat Input: procedure f of one argument, number of repetitions Output: f*…*f, n times (define (repeated f n) (if (= n 1) f (compose f (repeated f (- n 1))))) (define (compose f g) (lambda (x) (f (g x)))) 60

Repeat stream f,f*f,f*f*f,… = repeat = f,compose f,f,f,… with repeat (define f-series (cons-stream f f-series)) (define stream-repeat (cons-stream f (stream-map compose f-series stream-repeat))) We would like f to be a parameter 61

Repeat stream f,f*f,f*f*f,… = repeat = f,compose f,f,f,… with repeat (define (make-repeated f) (define f-series (cons-stream f f-series)) (define stream-repeat (cons-stream f (stream-map compose f-series stream-repeat))) stream-repeat) 62

Interleave 1,1,1,2,1,3,1,4,1,5,1,6,… (interleave ones integers) s0,t0,s1,t1,s2,t2,… interleave = s0,interleave (t, s from 2 nd position) (define (interleave s t) (if (stream-null? s) t (cons-stream (stream-car s) (interleave t (stream-cdr s))))) 63