I want to understand the following that swaps the values of i
and j
.
(setq i (prog1 j (setq j i)))
The documentation says FIRST
is evaluated first and is returned by prog1
, then BODY
is done later. What is set first then, i
or j
?
As the doc of prog1
tells you:
prog1
is a special form inC source code
.
(prog1 FIRST BODY...)
Eval
FIRST
andBODY
sequentially; return value fromFIRST
.The value of
FIRST
is saved during the evaluation of the remaining args, whose values are discarded.
"Sequentially" means first FIRST
is evaluated, then each of the forms in BODY...
. That's the order of evaluation. After all of that evaluation the value of FIRST
is returned. That's all there is to it.
In your example:
(setq i (prog1 j (setq j i)))
in (prog1 j (setq j i)
, FIRST
is j
, and BODY
is (setq j i)
.
However in the overall sexp, (setq i ...)
is first evaluated. setq
doesn't evaluate its first arg, i
, so the first thing evaluated is the (prog1 ...)
sexp.
In that sexp the first thing evaluated is j
. Then (setq j i)
is evaluated, which evaluates i
and sets j
to that value of i
. So j
was evaluated first, then j
was set to the value of i
.
But the initial value of j
, the result of the first evaluation, is what prog1
returns. And then the overall sexp sets the value of i
to that initial value of j
. So j
gets the initial value of i
and i
gets the initial value of j
. All thanks to prog1
.
See also my answer to your question about swapping characters in a string in [email protected]:
i
to that initial value of i
." Either I'm confused by the last paragraph (the rest of the description is clear) or the last variable in the quoted sentence should be changed to j
.
prog1
. Its doc is what talks about argumentFIRST
etc. This is a good question, because this idiom is a useful one for swapping variable values. Such swapping is maybe the most common use ofprog1
. Can't answer it till it gets reopened, however.