how to tail recurse

Subject: how to tail recurse
From: Louis-Dominique Dubeau <ldd@xxxxxxxxxxx>
Date: 22 Jul 1998 09:51:18 -0400
Hi,

In my first DSSSL project, I had the need for a function giving me the
depth of an element in the SGML structure.  I had this depth function
defined thus:

(define (depth node) 
  (let ((my-parent (parent node))) 
    (if (node-list-empty? my-parent) 
      0 
      (+ 1 (depth my-parent))))) 

This is clearly not tail recursive since it does something to the
value returned by the recursive call.  It occured to me that to make
it tail recursive, the solution was to carry the state forward as a
parameter of the recursive call.  The result is this:

(define (depth-recur node curdepth)  
  (let ((my-parent (parent node)))  
    (if (node-list-empty? my-parent)  
      curdepth 
      (depth-recur my-parent (+ 1 curdepth))))) 
 
(define (depth node) 
  (depth-recur node 0)) 

The above can be taken as an illustration on how to transform a
non-tail-recursive function into a tail-recursive one.  I think the
key idea there is to "carry the state forward as a parameter of the
recursive call".

I'm aware that the standard defines the ancestors function and that
depth could have been defined thus:

(define (depth node)
  (node-list-length (ancestors node)))

but when I tried that, Jade didn't like it so I must assume that
ancestors is not supported by Jade right now.

	Regards,
	ldd

PS: I've started using Jade and DSSSL 5 days ago so the above may
contain glaring errors.


 DSSSList info and archive:  http://www.mulberrytech.com/dsssl/dssslist


Current Thread
  • how to tail recurse
    • Louis-Dominique Dubeau - from mail1.ability.netby web4-1.ability.net (8.8.5/8.6.12) with ESMTP id JAA02198Wed, 22 Jul 1998 09:53:45 -0400 (EDT) <=
      • Toby Speight - from mail1.ability.netby web4-1.ability.net (8.8.5/8.6.12) with ESMTP id LAA05285Wed, 22 Jul 1998 11:02:12 -0400 (EDT)
      • Toby Speight - from mail1.ability.netby web4-1.ability.net (8.8.5/8.6.12) with ESMTP id LAA06170Wed, 22 Jul 1998 11:04:34 -0400 (EDT)
      • <Possible follow-ups>
      • Frank A. Christoph - from mail1.ability.netby web4-1.ability.net (8.8.5/8.6.12) with ESMTP id WAA25717Wed, 22 Jul 1998 22:04:43 -0400 (EDT)