List and list operations (continue).

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

Lists in Lisp and Scheme a. Lists are Lisp’s fundamental data structures, but there are others – Arrays, characters, strings, etc. – Common Lisp has moved.
1 Programming Languages (CS 550) Lecture Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
Lisp II. How EQUAL could be defined (defun equal (x y) ; this is how equal could be defined (cond ((numberp x) (= x y)) ((atom x) (eq x y)) ((atom y)
Functional Programming. Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends.
Lisp II. How EQUAL could be defined (defun equal (x y) ; this is how equal could be defined (cond ((numberp x) (= x y)) ((atom x) (eq x y)) ((atom y)
CSE 341 Lecture 16 More Scheme: lists; helpers; let/let*; higher-order functions; lambdas slides created by Marty Stepp
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.
6.001 SICP SICP – October Trees Trevor Darrell 32-D512 Office Hour: W web page:
6.001 SICP SICP – October HOPs, Lists, Trees Trevor Darrell 32-D512 Office Hour: W web page:
Functional programming: LISP Originally developed for symbolic computing Main motivation: include recursion (see McCarthy biographical excerpt on web site).
Data Abstraction… The truth comes out…. What we’re doing today… Abstraction ADT: Dotted Pair ADT: List Box and Pointer List Recursion Deep List Recursion.
6.001 SICP SICP – September ? 6001-Introduction Trevor Darrell 32-D web page: section.
6.001 SICP SICP – October Introduction Trevor Darrell 32-D512 Office Hour: W web page:
מבוא מורחב - שיעור 81 Lecture 8 Lists and list operations (continue).
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.
Quiz: Box and Pointer fun! (cons (cons (cons ‘hey (cons ‘there nil)) nil) (cons ‘wow nil)) (list ‘boo (append (list ‘hoo ‘hoo) (cons ‘see ‘me)))
PPL Pairs, lists and data abstraction. Data Abstraction? An interface: separate implementation from usage Think of the Map interface in Java: we know.
Spring 2008Programming Development Techniques 1 Topic 6 Hierarchical Data and the Closure Property Section September 2008.
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.
Practice session #6: 1. Sequence operations 2. Partial evaluation with currying 3. Lazy-lists.
Today’s topic: Abstraction Compound Data Data Abstractions: Isolate use of data abstraction from details of implementation Relationship between data abstraction.
Chapter 9: Functional Programming in a Typed Language.
CS 603: Programming Language Organization Lecture 10 Spring 2004 Department of Computer Science University of Alabama Joel Jones.
מבוא מורחב 1 Lecture #9. מבוא מורחב 2 Symbol: a primitive type constructors: (quote alpha) ==> quote is a special form. One argument: a name. selectors.
Recursive Data Structures and Grammars  Themes  Recursive Description of Data Structures  Recursive Definitions of Properties of Data Structures  Recursive.
PPL Lazy Lists. Midterm 2012 (define sum-vals (λ (ts) (if (ts-simple? ts) (ts-val ts) (accumulate + 0 (map ts-val (ts-inner-slots ts))))))
Fall 2008Programming Development Techniques 1 Topic 8 Sequences as Conventional Interfaces Section October 2008.
1 Data Abstraction. Pairs and Lists. (SICP Sections – 2.2.1)
PPL CPS. Moed A 2007 Solution (define scale-tree (λ (tree factor) (map (λ (sub-tree) (if (list? sub-tree) (scale-tree sub-tree factor) (* sub-tree.
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 8. Outline 1.The special form quote 2.Data abstraction: Trie 3.Alternative list: Triplets 4.Accumulate-n.
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 6. 2 List Utilities Scheme built-in procedures –(list x y z...) –(list-ref lst index) –(length lst) –(append.
PPL CPS. Moed A 2007 Solution (define scale-tree (λ (tree factor) (map (λ (sub-tree) (if (list? sub-tree) (scale-tree sub-tree factor) (* sub-tree.
מבוא מורחב שיעור 7 1 Lecture 7 Data Abstraction. Pairs and Lists. (Sections – 2.2.1)
1 Recursive Data Structures CS 270 Math Foundations of CS Jeremy Johnson.
CS 550 Programming Languages Jeremy Johnson
ML: a quasi-functional language with strong typing
Lecture 16 Streams continue Infinite Streams מבוא מורחב - שיעור 16.
6.001 SICP Variations on a Scheme
Pairs and Lists. Data Abstraction. SICP: Sections – 2.2.1
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.
Lists in Lisp and Scheme
Closures and Streams cs784(Prasad) L11Clos
CS 270 Math Foundations of CS Jeremy Johnson
6.001 SICP Data abstractions
Streams Sections 3.5.1,3.5.2 Pages
The Metacircular Evaluator
Lecture 18 Infinite Streams and
PPL Sequence Interface.
Lecture 18.
Lecture #8 מבוא מורחב.
6.001 SICP Streams – the lazy way
The Metacircular Evaluator (Continued)
Lecture #9 מבוא מורחב.
Streams and Lazy Evaluation in Lisp and Scheme
topics mutable data structures
6.001 SICP Data abstractions
Announcements Quiz 5 HW6 due October 23
Lecture #7 מבוא מורחב.
Today’s topics Abstractions Procedural Data
6.001 SICP Interpretation Parts of an interpreter
Lecture # , , , , מבוא מורחב.
list data list 만들기 list 사용하기 nil : list link :  * list -> list
Lecture 8: Recursing Lists CS150: Computer Science
Presentation transcript:

List and list operations (continue). Lecture 8 List and list operations (continue). מבוא מורחב - שיעור 8

Formal Definition of a List A list is either ‘() -- The empty list A pair whose cdr is a list. Note that lists are closed under the operations cons and cdr. מבוא מורחב - שיעור 8

More Elaborate Lists (list 1 2 3 4) (cons (list 1 2) (list 3 4)) (list (list 1 2) (list 3 4)) 1 2 3 4 1 3 4 2 1 3 4 2 מבוא מורחב - שיעור 8

The Predicate Null? (null? <z>) null? : anytype -> boolean #t if <z> evaluates to empty list #f otherwise (null? 2)  #f (null? (list 1))  #f (null? (cdr (list 1)))  #t (null? ’())  #t (null? null)  #t The beauty of list is that cdr allows us to easily move down a list, and we have a simple test to find out when we have reached the end, we get to the empty list, that is, to a list whose value is null. How do we check that we have reached the end, scheme supplies us with the predicate null? מבוא מורחב - שיעור 8

The Predicate Pair? pair? : anytype -> boolean (pair? <z>) #t if <z> evaluates to a pair #f otherwise. (pair? (cons 1 2))  #t (pair? (cons 1 (cons 1 2)))  #t (pair? (list 1))  #t (pair? ’())  #f (pair? 3)  #f (pair? pair?)  #f מבוא מורחב - שיעור 8

The Predicate Atom? atom? : anytype -> boolean (define (atom? z) (and (not (pair? z)) (not (null? z)))) (define (square x) (* x x)) (atom? square)  #t (atom? 3)  #t (atom? (cons 1 2))  #f Not a primitive procedure מבוא מורחב - שיעור 8

Working with lists: some basic list manipulation מבוא מורחב - שיעור 8

Cdring Down a List (define (list-ref lst n) (if (= n 0) (car lst) (list-ref (cdr lst) (- n 1)))) (list-ref (list 1 2 3) 0)  1 Error (list-ref (list 1 2 3) 3)  מבוא מורחב - שיעור 8

Cdring Down a List, another example (define (length lst) (if (null? lst) (+ 1 (length (cdr lst))))) מבוא מורחב - שיעור 8

Consing Up a List (define squares (list 1 4 9 16)) (define odds (list 1 3 5 7)) (append squares odds) (1 4 9 16 1 3 5 7) (append odds squares) (1 3 5 7 1 4 9 16) 1 2 3 4 list2 list1 Can’t make this pointer Change, so… (define (append list1 list2) (cond ((null? list1) list2) ; base (else (cons (car list1) ; recursion (append (cdr list1) list2))))) מבוא מורחב - שיעור 8

Append: process list1 list2 (define (append list1 list2) (cond ((null? list1) list2) ; base (else (cons (car list1) ; recursion (append (cdr list1) list2))))) (define list1 (list 1 2)) (define list2 (list 3 4)) 1 2 3 4 list2 list1 (append list1 list2) (cons 1 (append (2) list2)) (cons 1 (cons 2 (append () list2))) (cons 1 (cons 2 list2)) 1 2 (1 2 3 4) מבוא מורחב - שיעור 8

Reverse of a list cons (define (reverse lst) (cond ((null? lst) lst) (else ( (reverse (cdr lst)) ))))) cons (car lst) (reverse (list 1 2 3 4)) cons 1 4 3 2 (reverse (cdr lst)) Wishful thinking… (car lst) 4/7/2019

Reverse of a list (append ) (define (reverse lst) (cond ((null? lst) lst) (else ( (reverse (cdr lst)) ))))) append (list (car lst)) (reverse (list 1 2 3 4)) (reverse (cdr lst)) (list (car lst)) 4 3 2 1 (append ) Append: T(n) = c*n = (n) Reverse: T(n) = c*(n-1) + c*(n-2)+ … + c*1 = (n2) 4 3 2 1 4/7/2019

Enumerating (define (integers-between lo hi) (cond ((> lo hi) null) (else (cons lo (integers-between (+ 1 lo) hi))))) (integers-between 2 4) (cons 2 (integers-between 3 4))) (cons 2 (cons 3 (integers-between 4 4))) (cons 2 (cons 3 (cons 4 (integers-between 5 4)))) (cons 2 (cons 3 (cons 4 null))) (2 3 4) 2 3 4 מבוא מורחב - שיעור 8

Enumerate Squares (define (enumerate-squares from to) (cond ((> from to) '()) (else (cons (square from) (enumerate-squares (+ 1 from) to))))) (enumerate-squares 2 4) (cons 4 (enumerate-squares 3 4))) (cons 4 (cons 9 (enumerate-squares 4 4))) (cons 4 (cons 9 (cons 16 (enumerate-squares 5 4)))) (cons 4 (cons 9 (cons 16 ‘()))) (4 9 16) 4 9 16 מבוא מורחב - שיעור 8

Trees Abstract tree: a leaf (a node that has no children, and contains data) - is a tree an internal node (a node whose children are trees) – is a tree leaf 8 6 2 4 internal node Implementation of tree: a leaf - will be the data itself an internal node – will be a list of its children 2 4 6 8 מבוא מורחב - שיעור 8

Count Leaves of a Tree Strategy base case: count of an empty tree is 0 base case: count of a leaf is 1 recursive strategy: the count of a tree is the sum of the countleaves of each child in the tree. Implementation: (define (leaf? x) (atom? x)) מבוא מורחב - שיעור 8

Count Leaves (define (countleaves tree) (cond ((null? tree) 0) ;base case ((leaf? tree) 1) ;base case (else ;recursive case (+ (countleaves (car tree)) (countleaves (cdr tree)))))) (define my-tree (list 4 (list 5 7) 2)) 4 2 5 7 מבוא מורחב - שיעור 8

Countleaves my-tree (countleaves my-tree ) ==> 4 4 4 2 5 7 (cl (4 (5 7) 2)) 4 + (cl 4) (cl ((5 7) 2) ) 3 1 + (cl (5 7)) (cl (2)) 2 1 + (cl 5) (cl (7)) + (cl 2) (cl null) 1 + (cl 7) (cl null) 1 1 1 מבוא מורחב - שיעור 8

Enumerate-Leaves Goal: given a tree, produce a list of all the leaves Strategy base case: list of empty tree is empty list base case: list of a leaf is one element list otherwise, recursive strategy: build a new list from a list of the leaves of the first child and a list of the leaves of the rest of the children מבוא מורחב - שיעור 8

Enumerate-Leaves (define (enumerate-leaves tree) (cond ((null? tree) null) ;base case ((leaf? tree) ) ;base case (else ;recursive case ( (enumerate-leaves (car tree)) (enumerate-leaves (cdr tree)))))) מבוא מורחב - שיעור 8

Enumerate-Leaves (define (enumerate-leaves tree) (cond ((null? tree) null) ;base case ((leaf? tree) (list tree)) ;base case (else ;recursive case (append (enumerate-leaves (car tree)) (enumerate-leaves (cdr tree)))))) 4 2 5 7 4 2 5 7 מבוא מורחב - שיעור 8

Enumerate-leaves (el (4 (5 7) 2)) (4 5 7 2) ap (el 4) (el ((5 7) 2) ) (5 7 2) (4) ap (cl (5 7)) (el (2)) (5 7) (2) ap (el 5) (el (7)) ap (7) (el 2) (el nil) ap (el 7) (el nil) (5) (2) () (7) () מבוא מורחב - שיעור 8

Your Turn: Scale-tree Goal: given a tree, produce a new tree with all the leaves scaled Strategy base case: scale of empty tree is empty tree base case: scale of a leaf is product otherwise, recursive strategy: build a new tree from a scaled version of the first child and a scaled version of the rest of children מבוא מורחב - שיעור 8

Scale-tree (define (scale-tree tree factor) (cond ((null? tree) ) ;base case ((leaf? tree) ) (else ;recursive case (cons )))) null (* tree factor) (scale-tree (car tree) factor) (scale-tree (cdr tree) factor) מבוא מורחב - שיעור 8

List abstraction Find common high order patterns Distill them into high order procedures Use these procedures to simplify list operations Patterns: Mapping Filtering Accumulating מבוא מורחב - שיעור 8

Mapping (define (map proc lst) (if (null? lst) null (cons (proc (car lst)) (map proc (cdr lst))))) (define (square-list lst) (map square lst)) (define (scale-list lst c) (map (lambda (x) (* c x)) lst)) (scale-list (integers-between 1 5) 10) ==> (10 20 30 40 50) מבוא מורחב - שיעור 8

Mapping: process (map square (list 1 2 3)) (define (map proc lst) (if (null? lst) null (cons (proc (car lst)) (map proc (cdr lst))))) (map square (list 1 2 3)) (cons (square 1) (map square (list 2 3))) (cons 1 (map square (list 2 3))) (cons 1 (cons (square 2) (map square (list 3)))) (cons 1 (cons 4 (map square (list 3)))) (cons 1 (cons 4 (cons (square 3) (map square null)))) (cons 1 (cons 4 (cons 9 (map square null)))) (cons 1 (cons 4 (cons 9 null))) (1 4 9) מבוא מורחב - שיעור 8

Alternative Scale-tree Strategy base case: scale of empty tree is empty tree base case: scale of a leaf is product otherwise: a tree is a list of subtrees and use map. (define (scale-tree tree factor) (cond ((null? tree) null) ((leaf? tree) (* tree factor)) (else ;it’s a list of subtrees (map (lambda (child) (scale-tree child factor)) tree)))) מבוא מורחב - שיעור 8

We will see how to write such a procedure later! Generalized Mapping (map <proc> <list1>…<listn>) Returns a list in which proc is applied to the i-th elements of the lists respectively. (map + (list 1 2 3) (list 10 20 30) (list 100 200 300)) ==> (111 222 333) (map (lambda (x y) (+ x (* 2 y))) (list 1 2 3) (list 4 5 6)) ==> (9 12 15) We will see how to write such a procedure later! מבוא מורחב - שיעור 8

Filtering (define (filter pred lst) (cond ((null? lst) null) ((pred (car lst)) (cons (car lst) (filter pred (cdr lst)))) (else (filter pred (cdr lst))))) (filter odd? (integers-between 1 10)) (1 3 5 7 9) מבוא מורחב - שיעור 8

Filtering: process (filter odd? (list 1 2 3 4)) (define (filter pred lst) (cond ((null? lst) null) ((pred (car lst)) (cons (car lst) (filter pred (cdr lst)))) (else (filter pred (cdr lst))))) (filter odd? (list 1 2 3 4)) (cons 1 (filter odd? (list 2 3 4))) (cons 1 (filter odd? (list 3 4))) (cons 1 (cons 3 (filter odd? (list 4)))) (cons 1 (cons 3 (filter odd? null))) (cons 1 (cons 3 null)) (1 3) מבוא מורחב - שיעור 8

Finding all the Primes: Sieve of Eratosthenes (a.k.a. Beta) 100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85 84 83 82 81 80 79 78 77 76 75 74 73 72 71 60 69 68 67 66 65 64 63 62 61 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 XX 5 XX X 3 XX X 2 XX 7 מבוא מורחב - שיעור 8

.. And here’s how to do it! (define (sieve lst) (if (null? lst) ‘() (cons (car lst) (sieve (filter (lambda (x) (not (divisible? x (car lst)))) (cdr lst)))))) ==> (sieve (list 2 3 4 5 … 100)) (cons 2 (sieve (filter (lambda (x) (not (divisible? X 2) (list 3 4 5 …100 )))) מבוא מורחב - שיעור 8

How sieve works (define (sieve lst) (if (null? lst) ‘() (cons (car lst) (sieve (filter (lambda (x) (not (divisible? x (car lst)))) (cdr lst)))))) Sieve takes as argument a list of numbers L and returns a list M. Take x, the first element of L and make it the first element in M. Drop all numbers divisible by x from (cdr L). Call sieve on the resulting list, to generate the rest of M. מבוא מורחב - שיעור 8

What’s the time complexity of sieve? (define (sieve lst) (if (null? lst) ‘() (cons (car lst) (sieve (filter (lambda (x) (not (divisible? x (car lst)))) (cdr lst)))))) Assume lst is (list 2 3 ... n). How many times is filter called? (n) (number of primes < n) The Prime Number Theorem: (n) = Θ(n/log n) (For large n the constants are nearly 1) מבוא מורחב - שיעור 8

What’s the time complexity of sieve? (cont’) (define (sieve lst) (if (null? lst) ‘() (cons (car lst) (sieve (filter (lambda (x) (not (divisible? x (car lst)))) (cdr lst))))))  T(n) = O( ) n2/log n Filter is called Θ(n/log n) times Filter is called Θ(n/log n) times for primes p ≤ n/2 (n/2+1..n) = (n) - (n/2) = Θ(n/log n)  Each such call to filter does Ω(n/log n) work  T(n) = Ω( n2 /(log n)2 ) The problem is that filter has to scan all of the list! מבוא מורחב - שיעור 8

Another example Find the number of integers x in the range [1…100] s.t.: x * (x + 1) is divisible by 6. (length (filter _____________________________________ (map _________________________________ _________________________________)))) (lambda(n) (= 0 (remainder n 6))) (lambda(n) (* n (+ n 1))) (integers-between 1 100) 66 (about two thirds) Any bets on the result???? מבוא מורחב - שיעור 8

Accumulating Add up the elements of a list (define (add-up lst) (if (null? lst) (+ (car lst) (add-up (cdr lst))))) Multiply all the elements of a list (define (mult-all lst) (if (null? lst) 1 (* (car lst) (mult-all (cdr lst))))) (define (accumulate op init lst) (if (null? lst) init (op (car lst) (accumulate op init (cdr lst))))) מבוא מורחב - שיעור 8

Accumulating (cont.) el1 eln-1 eln init …….. op ... (define (accumulate op init lst) (if (null? lst) init (op (car lst) (accumulate op init (cdr lst))))) eln init op eln-1 el1 …….. ... (define (add-up lst) (accumulate + 0 lst)) (define (mult-all lst) (accumulate * 1 lst)) מבוא מורחב - שיעור 8