Subject: Re: how to tail recurse From: Toby Speight <Toby.Speight@xxxxxxxxxxxxxx> Date: 22 Jul 1998 16:02:50 +0100 |
LD> Louis-Dominique Dubeau <URL:mailto:ldd@xxxxxxxxxxx> => In article <q8r9ze804p.fsf@xxxxxxxxxxxxxxxxxxx>, LD wrote: LD> ... to make it tail recursive, the solution was to carry the state LD> forward as a parameter of the recursive call. The result is this: LD> LD> (define (depth-recur node curdepth) LD> (let ((my-parent (parent node))) LD> (if (node-list-empty? my-parent) LD> curdepth LD> (depth-recur my-parent (+ 1 curdepth))))) LD> LD> (define (depth node) LD> (depth-recur node 0)) You could save having to have two functions in either of two ways: 1. Use a default value for the depth argument: (define (depth node (curdepth 0)) (let ((my-parent (parent node))) (if (node-list-empty? my-parent) curdepth (depth my-parent (+ 1 curdepth))))) 2. Use named let (or letrec): (define (depth node) (let loop ((node node) (depth 0)) (if (node-list-empty? node) depth (loop (parent node) (+ 1 depth))))) The second is most useful when you don't want the extra parameter to be used externally. [P.S. Untested code - check before use!] -- DSSSList info and archive: http://www.mulberrytech.com/dsssl/dssslist
Current Thread |
---|
|
<- Previous | Index | Next -> |
---|---|---|
how to tail recurse, Louis-Dominique Dube | Thread | Re: how to tail recurse, Toby Speight |
how to tail recurse, Louis-Dominique Dube | Date | Re: how to tail recurse, Toby Speight |
Month |