The problem was:
We mentioned in the Encoding notes that
fold_left (flipped_cons, ) xswould give us the elements of
xsbut in the reverse order. So that's how we can express
reversein terms of
fold_left. How would you express
reversein terms of
This problem does have an elegant and concise solution, but it may be hard for you to figure it out. We think it will a useful exercise for you to try, anyway. Don't look at the hint until you've gotten really worked up about the problem. Before that, it probably will just be baffling. If your mind has really gotten its talons into the problem, though, the hint might be just what you need to break it open.
There are also other, less cool answers. Perhaps you'll find one of them first.
Even if you don't get any answer, we think the experience of working on the problem, and then understanding the answer when we reveal it, will be satisfying and worthwhile. It also fits our pedagogical purposes for some of the recurring themes of the class.
Here is a hint.
Suppose the list we want to reverse is
[10, 20, 30]. Applying
fold_right to this will begin by computing
f (30, z) for some
z that we specify. If we made the result of that be something like
30 & blah, or any larger structure that contained something of that form, it's not clear how we could, using just the resources of
fold_right, reach down into that structure and replace the
blah with some other element, as we'd evidently need to, since after the next step we should get
30 & (20 & blah). What we'd like instead is something like this:
30 & < >
< > isn't some value but rather a hole. Then with the next step, we want to plug into that hole
20 & < >, which contains its own hole. Getting:
30 & (20 & < >)
And so on. That is the key to the solution. The questions you need to answer, to turn this into something executable, are:
What is a hole? How can we implement it?
fbe, so that the result of the second step, namely
f (20, 30 & < >), is
30 & (20 & < >)?
Given that choice of
f, what should
zbe, so that the result of the first step, namely
f (30, z)is
30 & < >?
At the end of the
fold_right, we're going to end with something like
30 & (20 & (10 & < >)). But what we want is
[30, 20, 10]. How can we turn what we've gotten into what we want?
So now put it all together, and explain how to express
fold_rightand primitive syntax like
The ideas in Chapter 8 of The Little Schemer may help you see the answer to this problem.