Re: how to tail recurse

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
  • 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)