PLQ #11Done on:   Tuesday, April 2nd

Question 1 @ 2024-04-02 18:53

How do macros in an X programming language simplify the life of a language designer who wants to use X to implement a new language Y?


Question 2 @ 2024-04-02 18:55

Say that you want to implement a swap! that can swap the values of two boxes. It would look like this:

> (define b1 (box 1))
> (define b2 (box 2))
> (swap! b1 b2)
> (list (unbox b1) (unbox b2))
'(2 1)

What is the right tool for defining swap!?


Question 3 @ 2024-04-02 18:57

Say that you want to implement a swap! that can swap the values of two variables. It would look like this:

> (define x1 1)
> (define x2 2)
> (swap! x1 x2)
> (list x1 x2)
'(2 1)

What is the right tool for defining swap! now?


Question 4 @ 2024-04-02 18:59

The last two questions inspired your friend to implement a with-swapped thing that evaluates some code with two given boxes having their values temporarily swapped. Again, an example to demonstrate, and the implementation:

> (define b1 (box 1))
> (define b2 (box 2))
> (with-swapped b1 b2
    (list (unbox b1) (unbox b2)))
'(2 1)
> (list (unbox b1) (unbox b2))
'(1 2)

(define-syntax-rule (with-swapped B1 B2 body)
  (let ([v1 (unbox B1)]
        [v2 (unbox B2)])
    (set-box! B1 v2)
    (set-box! B2 v1)
    (let ([result body])
      (set-box! B1 v2)
      (set-box! B2 v1)
      result)))

What are the mistakes (or “poor choices”) in this piece of code?

(This question will be worth more than a normal one.)