Structure and
Interpretation
of Computer
Programs

Fall 2021
course
site
-->

Mon Oct 04

Questions about anything?

trees & lists ... revisited

Last time, a question was asked about how trees and lists worked ... and in particular how a tree with more than two children would work, since the cons structure in scheme only has two parts. I didn't answer that well, and I'd like to revisit that a bit more.

The discussion in the text section 2.2.2, "hierarchical structures", glosses over the point that in order to work with trees and answer questions like "how many children does that node have", we need to define a "representation" of a node, in the same way that we needed to define a representation of something like a "line segment" in an earlier assignment. We decide what part of the cons mean what, build that into an API, and then use that API consistently.

The function that we defined last class, count-leaves, is really treating each cons as a node that has two children and no "value" - no attached name. In that representation, only the terminal nodes can have "values", and there isn't a built-in notion of "how many children".

Let's take a look at simply scheme chapter 18 : trees for a more full featured version of what is typically meant by a tree, which each node can have a value (like a name) and a specific number of children.

aside

Discuss the problem with '(1 2 3 (list 4 5)) in scheme. Moral : only use list when it will be evaluated; don't mix quote (which stops evaluation) with list.

eight queens

Next I'd like to discuss exercise 2.42 - it's a classic, known as the n queens problem .

I have two attached files, one a warm-up that looks a the sequence functions (map, filter, flatmap, etc), and one my solution .

Notice how much power we've reached, starting with only a few built-in capabilities and building up from there. And notice that we've done this whole fairly tricky tree search in a pure-function way, without modifying any data structures after they were created.

Is it coincidence that the number of this problem is 42, the answer to life, the universe, and everything? Hmmm. Well, SICP was published after the Hitchhiker's Guide, so maybe not. ;)

https://cs.bennington.college /courses /fall2021 /sicp /notes /10-04
last modified Mon October 4 2021 3:08 am

attachments [paper clip]

  last modified size
TXT 2_42.scm Mon Oct 04 2021 02:53 am 25K
TXT fig2-5.png Mon Oct 04 2021 02:53 am 127K
TXT sequences.scm Mon Oct 04 2021 02:53 am 1.9K