1 / 15

6001 structure & interpretation of computer programs recitation 9/ october 15, 1997

Learn about dictionaries, pattern matching, and implementing dictionaries in computer programs. Explore examples of dictionaries and patterns in different programming languages. Understand rules, matches, and variables in pattern-based programming.

Download Presentation

6001 structure & interpretation of computer programs recitation 9/ october 15, 1997

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 6001structure & interpretation of computer programsrecitation 9/ october 15, 1997

  2. overview • today’s ideas • dictionaries • pattern matching • cross products

  3. dictionaries • model • a dictionary is a table that associates keys with values • each key is associated with at most one value • constructors • new: –> Dict • add: Dict x Key x Val –> Dict • observers • containsKey: Dict x Key –> Bool • lookup: Dict x Key –> Val • contract • (containsKey (new) k) ==> #f • (containsKey (add d k1 v) k2) ==> #t when k1 = k2, or whatever (containsKey d k2 v) evals to otherwise • (lookup (add d k1 v) k2) ==> v when k1 = k2, or whatever (lookup d k2 v) evals to otherwise • assume lookup is only called when dict contains keyand add is only called with keys not contained in dict

  4. implementing dictionaries • simple representation: association list • (define (lookup d k) (cadr (assq k d))) • orders of growth (in n, length of assoc list): • time to lookup: n • time to insert new entry: 1 • if list is sorted? • worst case is no better • but on average, only search half the list • better representations • can learn about these in algorithms course • tree: entries are sorted by key, and arranged on a tree • time is order (log n) to lookup • hash table • entries are stored in lists of buckets • each list is associated with an array element • hash function applied to key gives array index,designed to spread entries evenly so that lists are short • time is order (1) to lookup

  5. dictionary merge • a new operation • merge : Dict x Dict --> Dict • resulting dictionary contains the entries of both dictionaries • if the argument dictionaries have any common keys, they must agree on their values • otherwise merge fails • implementation • note use of special failure value • (define (merge d1 d2)(if (null? d1) d2 (let ((b (car d1)) (k1 (car b)) (v1 (cdr b))) (if (containsKey d2 k1) (if (equal? v1 (lookup d2 k1)) (merge (cdr d1) d2) ‘fail) (cons b (merge (cdr d1) d2)))))))

  6. using dictionaries • examples • browser cache: URLs to cached web pages • email client: aliases to email addresses • file directory: file name to file contents • dictionary packages • many programming languages provide built-in support for dictionary-like objects • Java’s util package has a dictionary class with several implementations, such as hash table • Scheme has some built-in procedures for handling association lists • assq : Key x List (Pair (Key, Val)) –> Pair (Key, Val) • (define al ‘(a.1 b.2 c.3)) • (assq ‘b al) ==> a.1

  7. patterns • definition • a pattern is a symbol or a list of symbols • each symbol is either an atom or a variable • a variable is prefixed with a question mark: ?v • instantiation • given a pattern and a dictionary from vars to atoms,we can generate a symbol or a list of symbols • example • pattern is (?greeting there ?name ) • dictionary is ((?greeting hello) (?name alice)) • result is (hello there alice) • matching • given some result and a pattern, can we find a dictionary? these are called matches • may be none or one • examples for datum (hello there alice) • pattern (?greeting there ?firstname) – one match • pattern (?greeting there ?firstname ?lastname) – no matches • pattern (?greeting ?name) – no matches

  8. tilde variables • new kind of variable • ~v is instantiated with a list of symbols • the elements of this list (not the list itself) are inserted when instantiated • example • pattern is (~greeting ?name ) • dictionary is ((~greeting (hello there)) (?name alice)) • result is (hello there alice) • ~v can be instantiated by an empty list • matching • how many matches now? • can have several matches for same pattern and datum • example datum (hello friend alice) • pattern (~greeting ~name) produces three matches, these: • ((~greeting (hello) (~name (friend alice))) • ((~greeting (hello friend) (~name (alice))) • and also these: • ((~greeting ()) (~name (hello friend alice))) • ((~greeting (hello friend alice) (~name ()))

  9. rules • a rule consists of • two patterns • one is used to generate matches (a list of dictionaries) – called the matching pattern • the other is used as a template to generate results – called the template • examples from toy Eliza program • (~a mother ~b) (tell me more about your mother) • ?x (why are you being short with me ?) • (~phrase) (what makes you say ~phrase ?) • yes (you sound confident) • example: dotted tail notation • (define (sum x . t) (if (null? t) x (+ x (sum t))) • how many matches for this kind of pattern? • nameless vars • no point giving names to vars not used in the template • so just use ? and ~ by themselves • note that template is not exactly a pattern: it can use ? and ~ as atoms

  10. how many? • how many results of applying a rule? • matching can produce 0, 1 or several dictionaries • instantiation always produces exactly one result from each pattern and dictionary • but two dictionaries may yield the same result • example • datum is (1 2) • pattern is (~a ~b) • template (~b ~a) • 3 matches (~a associated with (), (1), (1 2)) • but only 2 results: (1 2) and (2 1)

  11. multiply-occurring vars • what happens when a variable occurs twice? • given our definition of matching, answer is clear:must be matched to the same value in both places • implementation in problem set uses dictionary merging • example • (~ ~a ~ ~a ~) (youre repeating yourself) • (~ ?a ?a ~) (youre stammering) • (?x + ?x) (2 ?x) • (?x / ?x) (1)

  12. more elaborate rules • in the problem set, you’ll encounter • restriction rules • apply an arbitrary test to the dictionary before allowing match • user provides code for test as a procedure Dict –> Bool • general rules • get around simple instantiation mechanism • in problem set, user-supplied procedure constructs result from dictionary directly

  13. sequencing the application of rules • a rule-based system has • a set of rules, often very large • heuristics that determine which order to apply the rules in • which rule is applied first? • are rules applied repeatedly? • partial matches • rules may be applied against part of the input • for example, in arithmetic simplification want to reduce (x + x) to 2xwhatever context it appears in • so (y + x + x) should be simplified to (y + 2x)

  14. forming cross products • problem • given two lists, p and q, form the list consisting of all pairs pi.qjin order, where pi is the ith element of p and qj is the jth element of q • prelude: apply • (apply op l) applies the procedure op to the arguments given by the list l • (apply + ‘(1 2 3)) ==> 6 • a neat solution • first make a list from p by pairing each of its elements with all the elements of q(define (tensor p q) (map (lambda (pi) (map (lambda (qj) (cons pi qj)) q) p) • now append all the resulting lists together(define (cross p q) (apply append (tensor p q))) • puzzle • can you generalize this so that rather than just pairing pi and qj it applies someprocedure proc, giving a list of the results of evaluating (proc pi qj)? • can you eliminate all pairings that give a result satisfying some property? (example: proc is *, drop all zeros)

  15. student puzzle • for Wednesday • implement a procedure • remdups: List(t) x (t x t –> bool) –> List(t) • which given a list, returns a list containing the same elementsin the same order, but with duplicates removed • equality of elements is determined using the procedure argument • hint: use filter

More Related