[ACCEPTED]-what is the 'cons' to add an item to the end of the list?-common-lisp

Accepted answer
Score: 30

You could use append, but beware that it can lead 4 to bad performance if used in a loop or 3 on very long lists.

(append '(1 2 3) (list (+ 2 2)))

If performance is important, the 2 usual idiom is building lists by prepending 1 (using cons), then reverse (or nreverse).

Score: 8

If the "cons at the front, finish by 11 reversing" idiom isn't suitable for 10 you (if you. for example, need to pass the 9 list on to other functions DURING its construction), there's 8 also the "keep track of the end" trick. However, it's 7 probably cleaner to just build the list 6 by consing to the front of it, then finish 5 by using reverse or nreverse before finally 4 using it.

In essence, this allows you to 3 have the list in the right order while building 2 it, at the expense of needing to keep track 1 of it.

(defun track-tail (count)
  (let* ((list (cons 0 nil))
         (tail list))
    (loop for n from 1 below count
       do (progn
        (setf (cdr tail) (cons n nil))
        (setf tail (cdr tail))
        (format t "With n == ~d, the list is ~a~%" n list)))
    list))

This gives the following output:

CL-USER> (track-tail 5)
With n == 1, the list is (0 1)
With n == 2, the list is (0 1 2)
With n == 3, the list is (0 1 2 3)
With n == 4, the list is (0 1 2 3 4)
(0 1 2 3 4)
Score: 5

You can also use nconc to create the list, which 2 is like append, only it modifies the structure 1 of the input lists.

(nconc nlist (list (+ 2 2)))
Score: 5

You haven't specified the kind of Lisp, so 4 if you use Emacs Lisp and dash list manipulation 3 library, it has a function -snoc that returns 2 a new list with the element added to the 1 end. The name is reversed "cons".

(-snoc '(1 2) 3) ; (1 2 3)
Score: 3

This function might be useful in some situations, it 3 transparently appends a single element to 2 a list, i.e. it modifies the list but returns 1 the appended element (enclosed in a list):

(defun attach1 (lst x)
  (setf (cdr (last lst)) (cons x nil)))

;; (attach1 nlist (+ 2 2)) ; append without wrapping element to be added in a list
Score: 2

(append l (list e)) ; e is the element that 1 you want to add at the tail of a list

Score: 1

Cons-ing at the end of a list can be achieved 1 with this function:

(defun cons-last (lst x)
  (let ((y (copy-list lst))) (setf (cdr (last y)) (cons x nil)) y))

;; (cons-last nlist (+ 2 2))
Score: 1

If you are trying to add two lists for example 3 (1 2 3) + (1 2 3) here is the code (recursive)

(defun add-to-all (x y)
    (T (appendl (+ (first x) (first y)) (add-to-all (tail x) (tail y)) ))
)

If you are 2 trying to add an item to the end of the 1 second list, for example 3 + (1 2 3)

(defun add-to-all (x y)
  (cond ((null? y) nil)
    (T (appendl (+ (first x) (first y)) (add-to-all (tail x) (tail y)) ))
  )
)

More Related questions