0

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 ?

3
  • It is unclear what exactly you need to know. Please edit the question to make it clear what you need. Provide examples. Help us help you.
    – Trevoke
    Commented Jul 28, 2023 at 20:19
  • The question should be reopened. The question is about prog1. Its doc is what talks about argument FIRST 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 of prog1. Can't answer it till it gets reopened, however.
    – Drew
    Commented Jul 28, 2023 at 20:42
  • How was this closed with only one Close vote? And yet it takes multiple votes to Reopen? See this meta question.
    – Drew
    Commented Jul 28, 2023 at 20:43

1 Answer 1

2

As the doc of prog1 tells you:

prog1 is a special form in C source code.

(prog1 FIRST BODY...)

Eval FIRST and BODY sequentially; return value from FIRST.

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]:

2
  • "And then the overall sexp sets the value of 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.
    – Y. E.
    Commented Jul 29, 2023 at 7:06
  • @Y.E.: Typo (corrected). It should say "the overall sexp sets the value of i to that initial value of j." Thanks for noticing this.
    – Drew
    Commented Jul 29, 2023 at 14:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.