0

The following code snippet compiles under SBCL 2.2.3 (using Emacs/SLIME, C-c C-k), and the .fasl is loaded without errors.

On a subsequent call to test-sets in the REPL, the value of *evens* is set to *all*. Reading the documentation I could find, I cannot figure out why this happens and why calling test-sets would result in nil. Thank you in advance to everyone reading and/or responding.

(defun get-n (n) 
  "Return a list of integers from 0 up to n-1"
  (do ((i (1- n) (1- i)) 
       (res nil (cons i res))) 
      ((< i 0) res)))

(defun get-odd-n (n) 
  "Returns a list of odd integers from 1 up to n-1"
  (do ((i (1- n) (1- i)) 
       (res nil (if (oddp i) 
            (cons i res) res))) 
      ((< i 0) res)))

(defun get-even-n (n) 
  "Returns a list of even integers from 0 up to n-1"
  (do ((i (1- n) (1- i)) 
       (res nil (if (evenp i) 
            (cons i res) res))) 
      ((< i 0) res)))

(defconstant +n+ 10)
(defparameter *all* (get-n +n+))
(defparameter *odds* (get-odd-n +n+))
(defparameter *evens* (get-even-n +n+))

(defun test-sets () 
  "After compiling and loading .fasl, 
   why is *evens* altered after calling test-sets?"
  (and (equal (sort (intersection *evens* *all*) #'<) *evens*) 
       (equal (sort (intersection *odds* *all*) #'<) *odds*) 
       (equal (sort (union *odds* *evens*) #'<) *all*) 
       (equal (sort (set-difference *all* *odds* :test #'eql) #'<) *evens*) 
       (equal (sort (set-difference *all* *evens* :test #'eql) #'<) *odds*)))

1 Answers1

3

The UNION result shares list structure with its inputs.

SORT is destructive.

->

SORT changes the list structure, incl. the list structure *evens* points to.

Solution:

Either: define a non-destructive SORT

Or: or copy the list which is the argument to SORT

(sort (copy-list ...) ...)
Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
  • 1
    I think the relevant language in the HyperSpec is: [The result list may be eq to either list-1 or list-2 if appropriate.](http://www.lispworks.com/documentation/HyperSpec/Body/f_unionc.htm) – ad absurdum Apr 24 '22 at 17:35