[r6rs-discuss] [Formal] last-element behavior of for-each

AndrevanTonder andre at het.brown.edu
Fri Oct 6 17:10:35 EDT 2006


On Fri, 6 Oct 2006, Marcin 'Qrczak' Kowalczyk wrote:

> John Cowan <cowan at ccil.org> writes:
>
>> If we don't care about the results of the function on any of the
>> preceding elements, why are we likely to care on the final elements,
>> indeed?  I don't remember ever using for-each for anything but effect.
>
> But I agree that it's perhaps not worth the trouble, i.e. that
> programmers shouldn't expect a tail call here.

Is one extra line in the definition (assuming 1-arg case) that much more 
trouble, though?

With the current spec, one has the nice correspondence:

   (for-each f '(1 2 3)) == (begin (f 1) (f 2) (f 3))

whereas the alternative advocated here would be more complex, e.g.:

   (for-each f '(1 2 3)) == (begin (f 1) (f 2) (f 3) (unspecified))

The fact that, in the proposed modification, the last call to f is not a tail 
call, will adversely affect the space behavious of useful programs.  Here is a 
natural example:

   (define (print-list list)
     (for-each (lambda (node)
                 (if (not (pair? node))
                     (display node)
                     (print-list (car node))))
               list)

It is easy to exhibit an s-expression for which the r6rs semantics will have 
constant space behaviour, whereas the proposed modification would need space
proportional to the size of the s-expression to run.

I would therefore vote for the current tail-recurive specification.

Cheers
Andre



More information about the r6rs-discuss mailing list