CSC 153, Class 15: Pairs and Pair Structures Overview: * Behind the scenes: Storing values in memory * Cons cells and Pairs * Dotted Pairs * Lab * Reflection Notes: * Dead Internet connection -> No grading. Hopefully tonight. * Any questions on the CGI lab? * Reading: Vectors * Talk on Math Research Opportunities today at 4:30 * Exam 1 ready! Due next Wednesday. Ask questions frequently! ---------------------------------------- Every value you refer to in a program has to be stored in memory. Different values are represented in different ways. The things cons creates are pairs. A pair is a collection of two values (two words/memory cells) In each is a *reference* to another value. A refernce is simply the address of the other value in memory. Key thing for you to know: Every time you call cons, hyou allocate one of these pair boxes. Second key thing: These pairs may not be contiguous in memory To find the last element of a list, or the length of a list or ..., you need to repeatedly follow the second reference (the cdr). Observation: The second element of a pair need not be a reference to a pair or null. Question: How do you ever reclaim the memory allocated to a cons cell? Answer: Scheme is smart. It essentially keeps track of which cons cells are referenced and which are not and frees those which are not. The term for this activity is "garbage collection" Back to the observation: If the second element of a pair need not be list or null, how do we distinguish between the different kinds of pairs? The designers of Scheme decided that it was a Pain in the Neck to go through a list twice to print it out. To print a list: * Print an open paren * Print each element in turn * Pray that the last thing is null * Print a close paren when the null is reached If the last thing is not null, print a dot first to show that it's not a list. ---------------------------------------- Why "car" and "cdr"? On the computer on which Lisp was first implemented, there was an instruction to load a pair of values into two registers (address and decrement registers). To get the first of the two values, you took the contents of the address register (CAR). To get the second, you took the contents of the decrement register (CDR). ---------------------------------------- Reflection How did you write listp? Here's how Arjun did (define listp? (lambda (pair) (if (pair? (cdr pair)) (listp? (cdr pair)) (if (null? (cdr pair)) #t #f)))) What's wrong? (Incorrect, bad style, or inelegant) * Elegance: Nested ifs rather than conds * Correctness: What if pair is not a pair? Crashes and burns. * (if test #t #f) is longhand for test Here's how Oge did (define listp? (lambda (thingy) (if (null? thingy) #t (and (pair? thingy) (listp? (cdr thingy)))))) What's wrong? (Inelegant) (define listp? (lambda (thingy) (or (null? thingy) (and (pair? thingy) (listp? (cdr thingy))))))