[plt-scheme] safe for space idiom

From: Doug Orleans (dougorleans at gmail.com)
Date: Sun Mar 30 20:54:13 EDT 2008

I often find myself in the situation where I want to write code that
has roughly this shape:

(let loop ()
  (cond ((and a? b?)
         b)
        ((and a? c?)
         c
         (loop))
        (else
         d
         (loop))))

The repeated a? test seems ugly, though, and I want to factor it out:

(let loop ()
  (cond (a? (cond (b?
                   b)
                  (c?
                   c
                   (loop))
                  (else
                   d
                   (loop))))
        (else
         d
         (loop))))

But now I have d repeated.  I could use non-local return:

(let/ec return
  (let loop ()
    (when a?
      (when b?
        (return b))
      (when c?
        c
        (loop)))
    d
    (loop)))

My question is, is this safe for space?  The c (loop) is not in tail
position, so my guess is no.  Is there some other way to write this
that is safe for space but doesn't repeat anything?

--dougorleans at gmail.com


Posted on the users mailing list.