More Then there's the grandmother of all tree recursions 

Forum: U Chicago, Com Sci 221, autumn 2000
Re: News Assignment #7, due Monday 20 November (Mike O'Donnell)
Re: Warning Defining reduce from reduce-tree is subtle with nested lists (Mike O'Donnell)
Date: 2000, Nov 19
From: Mike O'Donnell <odonnell@cs.uchicago.edu>

If you're working furiously to finish the assignment, skip this message for now, and read it later. This is some fairly advanced stuff, going beyond the material really needed for the assignment, for those who are interested in following higher-order programming even farther.

Although the full solution for nested lists in problem #2 is feasible, it's not terribly elegant. That's why I will be thoroughly satisfied with the unnested solution. There is an even more general mechanism for recursion on trees, which provides an elegant way of defining reduce on nested lists. It looks like this:

(define (reduce-tree-with-context op atomval)

  (letrec ((rtc

               (lambda (treein context)


                        (cond ((pair? treein)  (op (rtc (car treein) 'left)
                                                   (rtc (cdr treein) 'right)
                                               )
                              )

                              (#t              (atomval treein))

                        )
                      )
                    ))

                 (lambda (treein) (rtc treein 'root))
           )
         )
The extra argument, context, lets the recursively defined function take into account whether it's working on a left or right subtree, or the root. I haven't debugged this at all, but I think it's essentially right. If my old reduce-tree is the mother of all higher-order functions to produce operations on binary trees, perhaps reduce-tree-with-context is the grandmother.

Then, there's the great-...-grandmother. You can beef the definition up to provide each recursive call to rtc with the whole path to its subtree (the global context), rather than just the last link on that path (the local context). But that method makes it more complicated to do things for which the context doesn't matter. Then, with some more thought, you can produce one definition that lets you compute exactly the amount of context that is relevant, and pass it down. This stuff never ends.



Mike O'D.


to: "Then there's the grandmother of all tree recursions"