What is the difference between (list nil) and '(nil) in Lisp?

First of all, let me say that I am new to Lisp. Honestly, I have been a newbie for some time, but there are many more things that I don’t know well.

While I was writing this question , I came up with a strange error in my code.

Here is a function that will return a list (0 1 ... n)with an added list e. It uses rplacdto track the last item to avoid the final call last.

For example, (foo 4 '(x))returns (0 1 2 3 4 x).

The "head" is stored in a, which is not easy nil, because there is only one niland is never copied (if I understand correctly), so I can’t just add it nil.

(defun foo (n e)
    (let* ((a (list nil)) (tail a))
        (loop for i to n
              do (rplacd tail (setf tail (list i)))
              finally (rplacd tail (setf tail e))
              (return (cdr a)))))

(defun bar (n e)
    (let* ((a '(nil)) (tail a))
        (loop for i to n
              do (rplacd tail (setf tail (list i)))
              finally (rplacd tail (setf tail e))
              (return (cdr a)))))

(list nil) '(nil) bar. foo , , bar nil.

, cdr of a nil, . , (setf x '(nil)) (rplacd x 1), (nil . 1), , .

+4
2

"(nil) (list nil) , , . - Common Lisp. . http://l1sp.org/cl/3.2.2.3 http://l1sp.org/cl/quote. , :" : undefined, ( ) ".

+5

. :

(defun test (&optional (arg '(0)))
  (setf (car arg) (1+ (car arg)))
  (car arg))

(defun test2 ()
  '(0))

, (0) ?

  • :

    (test) ; ==> Error, into the debugger we go
    
  • cons ( )

    (test2) ; ==> (0)
    (test)  ; ==> 1
    (test)  ; ==> 2
    (test)  ; ==> 3
    (test2) ; ==> (0)
    
  • , , :

    (test2) ; ==> (0)
    (test)  ; ==> 1
    (test)  ; ==> 2
    (test)  ; ==> 3
    (test2) ; ==> (3)
    

. , .

CLISP . SBCL, , , , (cdr '(0)) . , "undefined".

CLHS

: undefined, ( ) .

+3

Source: https://habr.com/ru/post/1584804/


All Articles