notes36 - deep-map to look more like a binary tree program:...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
Car/cdr recursion Consider the deep list ((a b) (c d)) . Ordinarily we would draw its box and pointer diagram with a horizontal spine at the top and the sublists beneath the spine: But imagine that we grab the frst pair oF this structure and “shake” it so that the pairs Fall down as Far as they can. We’d end up with this diagram: Note that these two diagrams represent the same list! They have the same pairs, with the same links From one pair to another. It’s just the position oF the pairs on the page that’s di±erent. But in this new picture, the structure looks a lot like a binary tree, in which the branch nodes are pairs and the leaF nodes are atoms (non-pairs). The “leFt branch” oF each pair is its car , and the “right branch” is its cdr . With this metaphor, we can rewrite
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: deep-map to look more like a binary tree program: ;;;;; In file cs61a/lectures/2.2/tree3.scm (define (deep-map fn xmas) (cond ((null? xmas) ()) ((pair? xmas) (cons (deep-map fn (car xmas)) (deep-map fn (cdr xmas)))) (else (fn xmas)))) (The Formal parameter xmas reects the Fact that the picture looks kind oF like a Christmas tree.) This procedure strongly violates data abstraction! Ordinarily when dealing with lists, we write programs that treat the car and the cdr dierently, reecting the Fact that the car oF a pair is a list element, whereas the cdr is a sublist. But here we treat the car and the cdr identically. One advantage oF this approach is that it works even For improper lists: > (deep-map square ((3 . 4) (5 6)) ((9 . 16) (25 36)) 302...
View Full Document

This note was uploaded on 02/17/2010 for the course COMPUTER S 26275 taught by Professor Harvey,b during the Spring '10 term at University of California, Berkeley.

Ask a homework question - tutors are online