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 |
---|
|
<- Previous | Index | Next -> |
---|---|---|
Re: Recreating length-specs, Richard Light | Thread | Re: how to tail recurse, Toby Speight |
Re: duration, Brandon Ibach | Date | Re: how to tail recurse, Toby Speight |
Month |