Questions about anything?
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.
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
.
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. ;)
last modified | size | ||
2_42.scm | Mon Oct 04 2021 02:53 am | 25K | |
fig2-5.png | Mon Oct 04 2021 02:53 am | 127K | |
sequences.scm | Mon Oct 04 2021 02:53 am | 1.9K |