notes05s - 1 CS61ANotes04Lists[Solutionsv1.0] PairUp!

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
CS61A Notes 04 – Lists [Solutions v1.0] Pair Up! QUESTIONS: What do the following evaluate to? (define u (cons 2 3)) (define w (cons 5 6)) (define x (cons u w)) (define y (cons w x)) (define z (cons 3 y)) 1. u, w, x, y, z (write them out in Scheme’s notation) u: (2 . 3) w: (5 . 6) x: ((2 . 3) 5 . 6) y: ((5 . 6) (2 . 3) 5 . 6) z: (3 (5 . 6) (2 . 3) 5 . 6) Note: when you type this into STk, y and z look weird; I’m not sure why right now, but I’ll look into it. As data structures, they still work fine. 2. (car y) (5 . 6) 3. (car (car y)) 5 4. (cdr (car (cdr (cdr z)))) 3 5. (+ (cdr (car y)) (cdr (car (cdr z)))) 12 6. (cons z u) ((3 (5 . 6) (2 . 3) 5 . 6) 2 . 3) 7. (cons (car (cdr y)) (cons (car (car x)) (car (car (cdr z))))) ((2 . 3) 2 . 5) Then Came Lists QUESTIONS: 1. Define a procedure  list-4  that takes in 4 elements and outputs a list equivalent to one created by  calling list. (define (list-4 e1 e2 e3 e4) (cons e1 (cons e2 (cons e3 (cons e4 ‘()))))) 2. Define a procedure  length  that takes in a list and returns the number of elements within the list. (define (length ls) (if (null? ls) 0 (+ 1 (length (cdr ls))))) Chung Wu; CS61A, Spring 2004 1
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
3. Define a procedure  list?  that takes in something and returns  #t  if it’s a list,  #f  otherwise. (define (list? ls) (or (null? ls) (and (pair? ls) (list? (cdr ls))))) Where’s the base case?! 4. Define  append  for two lists. (define (append ls1 ls2) (if (null? ls1) ls2 (cons (car ls1) (append (cdr ls1) ls2)))) 5. Suppose we have  x  bound to a mysterious element.  All we know is this: (list? x) ==> #t (pair? x) ==> #f What is  x ? The only thing that’s a list but not a pair is ‘(), the null list. 6. Add in procedure calls to get the desired results.  The blanks don’t need to have anything: ( cons ‘a ‘(b c d e)) ==> (a b c d e) ( append ‘(cs61a is) (list ‘cool ) ) ==> (cs61a is cool) ( cons ‘(back to) ‘(save the universe)) ==> ((back to) save the universe) ( cons ‘(I keep the wolf) (car ‘((from the door)) ) ) ==> ((I keep the wolf) from the door) 7. Define a procedure  (insert-after item mark ls)  which inserts 
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 5

notes05s - 1 CS61ANotes04Lists[Solutionsv1.0] PairUp!

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online