I'm having difficulty understanding what's going on with The Little Schemer's evens-only*&co
example on page 145.
Here's the code:
(define evens-only*&co
(lambda (l col)
(cond
((null? l)
(col '() 1 0))
((atom? (car l))
(cond
((even? (car l))
(evens-only*&co (cdr l)
(lambda (newl product sum)
(col (cons (car l) newl)
(opx (car l) product)
sum))))
(else
(evens-only*&co (cdr l)
(lambda (newl product sum)
(col newl product (op+ (car l) sum)))))))
(else
(evens-only*&co (car l)
(lambda (newl product sum)
(evens-only*&co (cdr l)
(lambda (dnewl dproduct dsum)
(col (cons newl dnewl)
(opx product dproduct)
(op+ sum dsum))))))))))
The initial col
can be:
(define evens-results
(lambda (newl product sum)
(cons sum (cons product newl))))
What I'm not getting is, with l
as '((1) 2 3)
, it goes immediately into the final else
with (car l)
as (1)
and (cdr l)
as (2 3)
. Good, but my mind goes blank trying to sort out the dnewl
, dproduct
, dsum
from the newl
, product
, sum
. It also would be helpful if somebody could coach me on how to set up DrRacket or Chez Scheme or MIT-Scheme for running a stepper.
But maybe I'm spazzing too early. Is any beginner reading this for the first time actually supposed to understand this wild continuation?
In equational pseudocode (a KRC-like notation, writing
f x y
for the call(f x y)
, where it is unambiguous), this isThis is a CPS code which collects all evens from the input nested list (i.e. a tree) while preserving the tree structure, and also finds the product of all the evens; as for the non-evens, it sums them up:
if
l
is an empty list, the three basic (identity) values are passed as arguments to col;if
(car l)
is an even number, the results of processing the(cdr l)
arenewl
,product
andsum
, and then they are passed as arguments tocol
while the first two are augmented by consing ⁄ multiplying with the(car l)
(the even number);if
(car l)
is an atom which is not an even number, the results of processing the(cdr l)
arenewl
,product
andsum
, and then they are passed as arguments tocol
with the third one augmented by summing with the(car l)
(the non-even number atom);if
(car l)
is a list, the results of processing the(car l)
areanewl
,aproduct
andasum
, and then the results of processing the(cdr l)
arednewl
,dproduct
anddsum
, and then the three combined results are passed as arguments tocol
.[]
,1
and0
of the base case are the identity elements of the monoids of lists, numbers under multiplication, and numbers under addition, respectively. This just means special values that don't change the result, when combined into it.As an illustration, for
'((5) 2 3 4)
(which is close to the example in the question), it creates the calculationSimilar to my other answer (to a sister question), here's another way to write this, with a patter-matching pseudocode (with guards):
The economy (and diversity) of this notation really makes it all much clearer, easier to just see instead of getting lost in the word salad of long names for functions and variables alike, with parens overloaded as syntactic separators for list data, clause groupings (like in
cond
expressions), name bindings (inlambda
expressions) and function call designators all looking exactly alike. The same uniformity of S-expressions notation so conducive to the ease of manipulation by a machine (i.e. lisp'sread
and macros) is what's detrimental to the human readability of it.I have been reading How To Design Programs (felleisen et.al.). I am going through the section where they define local definitions. I have written a code that implements the above evens-only&co using a local definition. Here's what I wrote:
For testing, when i enter (evens-only&co '((9 1 2 8) 3 10 ((9 9) 7 6) 2)) , it returns '(38 1920 (2 8) 10 (() 6) 2) as expected in the little schemer. But, my code fails in one condition: when there are no even numbers at all, the product of evens is still shown as 1. For example (evens-only&co '((9 1) 3 ((9 9) 7 ))) returns '(38 1 () (())). I guess i will need an additional function to rectify this. @melwasul: If you are not familiar with the local definition, sorry to post this here. I suggest you read HTDP too. It's an excellent book for beginners. But the guys who are experts in scheme can please post their comments on my code as well. Is my understanding of the local definition correct?
The answer by Jon O. is a really great in-depth explanation of underlying concepts. Though for me (and hopefully, for some other people too), understanding of concepts like this is a lot more easier when they have a visual representation.
So, I have prepared two flow-charts (similar to ones I did for
multirember&co
, untangling what is happening during the call ofevens-only*&co
given
l
is:and
col
is:One flow-chart, reflecting how variables relate in different steps of recursion: Second flow-chart, showing the actual values, being passed:
My hope is, that this answer will be a decent addition to the Jon's explanation above.
I found this section confusing on first reading too, and only started to get it after I'd read up elsewhere about continuations and continuation-passing style (which is what this is).
At the risk of explaining something that you already get, one way of looking at it that helped me is to think of the "collector" or "continuation" as replacing the normal way for the function to return values. In the normal style of programming, you call a function, receive a value, and do something with it in the caller. For example, the standard recursive
length
function includes the expression(+ 1 (length (cdr list)))
for the non-empty case. That means that once(length (cdr list))
returns a value, there's a computation waiting to happen with whatever value it produces, which we could think of as(+ 1 [returned value])
. In normal programming, the interpreter keeps track of these pending computations, which tend to "stack up", as you can see in the first couple of chapters of the book. For example, in calculating the length of a list recursively we have a nest of "waiting computations" as many levels deep as the list is long.In continuation-passing style, instead of calling a function and using the returned result in the calling function, we tell the function what to do when it produces its value by providing it with a "continuation" to call. (This is similar to what you have to do with callbacks in asynchronous Javascript programming, for example: instead of writing
result = someFunction();
you writesomeFunction(function (result) { ... })
, and all of the code that usesresult
goes inside the callback function).Here's
length
in continuation-passing style, just for comparison. I've called the continuation parameterreturn
, which should suggest how it functions here, but remember that it's just a normal Scheme variable like any other. (Often the continuation parameter is calledk
in this style).There is a helpful tip for reading this kind of code in an article on continuations by Little Schemer co-author Dan Friedman. (See section II-5 beginning on page 8). Paraphrasing, here's what the
else
clause above says:Note that this is almost exactly what the interpreter has to do in evaluating
(+ 1 (length (cdr lis)))
in the normal version of the function (except that it doesn't have to give a name to the intermediate result(length (cdr lis))
. By passing around the continuations or callbacks we've made the control flow (and the names of intermediate values) explicit, instead of having the interpreter keep track of it.Let's apply this method to each clause in
evens-only*&co
. It's slightly complicated here by the fact that this function produces three values rather than one: the nested list with odd numbers removed; the product of the even numbers; and the sum of the odd numbers. Here's the first clause, where(car l)
is known to be an even number:Here's the case where the head of the list is an odd number:
As before, but pass the same values of
newl
andproduct
to the continuation (i.e. "return" them), along with the sum ofsum
and the head of the list, since we're summing up odd numbers.And here's the last one, where
(car l)
is a nested list, and which is slightly complicated by the double recursion:Notice: each time we make a recursive call, we construct a new continuation for the recursive call, which "closes over" the current values of the argument,
l
, and the return continuation -col
, in other words, you can think of the chain of continuations which we build up during the recursion as modelling the "call stack" of a more conventionally written function!Hope that gives part of an answer to your question. If I've gone a little overboard, it's only because I thought that, after recursion itself, continuations are the second really neat, mind-expanding idea in The Little Schemer and programming in general.