0

Consider these two similar procedures:

(define (append-internal-cons obj)
  (let ((local-var (cons 1 '()) ))
    (append! local-var (list obj))
    local-var))

(define (append-internal-no-cons obj)
  (let ((local-var '(1) ))
    (append! local-var (list obj))
    local-var))

Given these two helper procedures:

(define (append! x y)
  (set-cdr! (last-pair x) y)
            x)
(define (last-pair ls)
  (if (null? (cdr ls))
             ls
             (last-pair (cdr ls))))

Calling the first one three times yields expected results: a list containing 1 and whatever obj we passed in.

(append-internal-cons 2) ;; (1 2)
(append-internal-cons 3) ;; (1 3)
(append-internal-cons 4) ;; (1 4)

I would expect calling the second version three times to yield the same results, but it doesn't.

(append-internal-no-cons 2) ;; (1 2)
(append-internal-no-cons 3) ;; (1 2 3)
(append-internal-no-cons 4) ;; (1 2 3 4)

Shouldn't the behavior of the two procedures be the same?

Will Ness
  • 70,110
  • 9
  • 98
  • 181
plafer
  • 185
  • 12
  • I could be wrong, but I believe mutating quoted literals is undefined behavior in the Scheme standard. Therefore, it is valid for an implementation to exhibit this behavior, but not all implementations will behave the same. – Alexis King May 28 '16 at 02:45
  • 1
    Mutating literals are not allowed in the Scheme standard. A scheme implementation is free to use one object for all occurrences of `'(1)` so this violation might even change other places. Most implementations don't signal am error since it's not required so you get unexpected behavior from a non scheme program (code that violates the report is not Scheme code) – Sylwester May 28 '16 at 10:41

0 Answers0