[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Multiple values passed as single argument to procedure

From: Mark H Weaver
Subject: Re: Multiple values passed as single argument to procedure
Date: Sun, 11 Jun 2017 17:31:59 -0400
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/25.2 (gnu/linux)

I wrote:

> Use 'call-with-values', 'let-values', or 'receive' to call a procedure
> that returns multiple values (or no values).
> If you do not use one of the above forms (or a macro that expands to one
> of them) to call a procedure that returns multiple values, then Guile
> will discard all but the first result.  Note that this is a
> Guile-specific extension.  Other Scheme implementations may behave
> differently (e.g. report an error) if multiple values (or no values) are
> returned to a procedure call that was not done using one of the forms
> listed above.

I forgot to mention that procedure calls in "tail position" are a
special case known as "tail calls".  In Scheme such a call is
semantically a "GOTO with arguments".  In such cases, the caller
procedure (let's call it FOO) has nothing left to do after its callee
(let's call it BAR) returns, and can simply arrange for BAR to return
its values directly to the caller of FOO.  In such cases, BAR can return
as many values as FOO's caller is prepared to accept.

For example:

  (define (div-and-mod x y)
    (if (negative? y)
        (ceiling/ x y)
        (floor/   x y)))
  (define (div x y)
    (let-values (((q r) (div-and-mod x y)))

Here, both 'floor/' and 'ceiling/' return two values (see the Guile
manual).  Since both of those procedures are called from tail position
in 'div-and-mod', they are tail calls (semantically GOTO with
arguments), and they return their values directly to the caller of

FYI, the 'div-and-mod' and 'div' defined above are equivalent to the
standard procedures of the same name in R6RS scheme, and to 'euclidean/'
and 'euclidean-quotient' included in core Guile.

Incidentally, the fact that tail calls are semantically GOTOs with
arguments, and that this behavior is guaranteed and not a mere "tail
call optimization", is the reason that we are able to write loops in
Scheme as recursive calls without using unbounded stack space.  In fact,
Scheme has no loop facility in the core language.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]