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*)))
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 ...) ...)