Lisp - append to a list
Asked Answered
G

1

6

I am new to lisp. I didn't properly understand how to implement append function on a list. I tried the following program.

(defvar temp)
(setq temp '())
(append temp (logxor 1 0))

temp seems to store only NIL value when it should be storing 1 in it.

Goddamned answered 8/3, 2015 at 15:42 Comment(0)
A
11

append returns the new value, it does not modify its arguments. You need to use setq:

(setq temp (append temp (list 1)))

or push (which adds to the beginning of the list, not the end!):

(push 1 temp)

You can also use nconc for destructive appending, but you will still need setq because you cannot destructively append to nil:

(defparameter temp nil)
(append temp '(1))
;; returns (1) but `temp` is still empty
(nconc temp '(1))
;; also returns (1) but `temp` is still empty
(setq temp (append temp (list 2)))
;; now temp is (2)
(append temp '(1))
;; returns (2 1) but `temp` is still (2)
(nconc temp '(1))
;; returns (2 1) and `temp` is now (2 1)

please note that one should not use quoted lists (like '(1)) when one plans to destructively append to them using nconc, see Why does an elisp local variable keep its value in this case? for more information and links, especially Issue CONSTANT-MODIFICATION.

Automat answered 8/3, 2015 at 16:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.