Can install a car! and set-cdr! be implemented as macros?

Is it possible to implement set-car! and set-cdr! portable as macros using set! in the circuit? Or will it require special access to the underlying storage system?

I ask because I am implementing my own Schema interpreter, and I would like to have as much schema code as possible.

My first attempt at set-cdr! was:

 (define-syntax set-cdr! (syntax-rules () ((set-cdr! location value) (set! location (cons (car location) value))))) 

This basically works, but not for circular lists:

 #; mickey> (define x (list 1 2)) #; mickey> x (1 2) #; mickey> (set-cdr! xx) #; mickey> x (1 1 2) 

Wrapping the macro body in let didn't help me either, because when I do (set! (cons (car location) value) , then value already evaluated as '(1 2) .

+4
source share
3 answers

IN

 (set! location (cons (car location) value)) 

the expression (cons (car location) value) highlights a new pair.

The goal of set-cdr! - change an existing pair.

Thus, the implementation of set-cdr! Requires β€œspecial” access to the underlying repository.

+4
source

Here is an example implementation of Cons, Car, Cdr, Set-car! and Set-cdr! using closure.

 (define (Cons xy) (lambda (message . val) (cond [(eq? message 'car) x] [(eq? message 'cdr) y] [(eq? message 'set-car!) (set! x (car val))] [(eq? message 'set-cdr!) (set! y (car val))] [else 'unknown-message]))) (define (Car pair) (pair 'car)) (define (Cdr pair) (pair 'cdr)) (define (Set-cdr! pair val) (pair 'set-cdr! val)) (define (Set-car! pair val) (pair 'set-car! val)) (define p (Cons 1 2)) (Car p) (Cdr p) (Set-car! p 3) (Car p) (Set-cdr! p 4) (Cdr p) 
+2
source

Basically you can implement a set! without set !, but I don’t think you can implement set-car! / set-cdr! without mutation pairs or simulating pairs (for example, an example of co-assembly)

Since it seems that you are doing your implementation of the Scheme on the Scheme, I would use set-car! / Set-cdr! implement it in the interpreter or simply not implement them at all. I would start by defining if, quote, pair ?, eq ?, cons, car, and cdr (similar to LISP Roots , but more schematically) to have a basic minimal implementation to start with, and then further improve it.

In any case .. Your implementation, if you implement it, should be able to do this:

 (define odds (list 1 3 5 7 9 11)) (set-car! (cddr odds) #f) odds ===> (1 3 #f 7 9 11) 
+1
source

All Articles