Take the 2-minute tour ×

Here's what I have so far:

(defun append-all(x L)
  (if (null L)
    (cons (append (car L) x) (append-all x (cdr L))))


(append-all '3 '((1) (2 1) (2)))

((1 . 3) (2 1 . 3) (2 . 3))


((1 3) (2 1 3) (2 3))

This is a helper function, so the fact that it is a linked list seems to be causing me problems.


edit: fixed recursive call

share|improve this question

4 Answers 4

up vote 2 down vote accepted

In your code, change this part:

(append (car L) x)

To this:

(append (car L) (list x))

It wasn't working before because append should receive two lists as parameters, not a list and an element.

share|improve this answer
(defun append-all (item list)
  "Appends ITEM to each sublist of LIST"
  (flet ((circular-list (item)
           (let ((list2 (list item)))
             (nconc list2 list2))))
    (mapcar #'append
            (circular-list (list item)))))
share|improve this answer
@wvxvw: I changed it to use NCONC, thanks. –  Rainer Joswig Jan 23 '13 at 13:03
Interesting trick. However flet now is not needed (you can just move mapcar inside the let and use list2 directly), if instead it's there for readability then it would be IMO even better moving (list item) out of it so that the call becomes (circular-list (list item)) –  6502 Jan 23 '13 at 16:33
@6502: I think using sub-functions in Lisp to increase readability is underrated. If it is of general utility, then it makes sense to move it to the top-level. Having a function already makes that easier... –  Rainer Joswig Jan 23 '13 at 16:52
I agree... but I'd use (flet ((circular-list (x) (let ((list2 (list x)) ...). A circular list with element x is more useful than a circular list where element is (list x). –  6502 Jan 23 '13 at 17:11
@6502: that makes sense... –  Rainer Joswig Jan 23 '13 at 17:20

If you'd rather not do the recursion yourself, this should also work:

(defun append-all (x L)
  (mapcar #'(lambda (l) (append l (list x))) L))
share|improve this answer
Note that with standard reader case, all symbols are upcased, so l and L denote the same symbol name. In the shown code, it works as expected, since L is shadowed. –  Svante Jan 22 '13 at 22:31
Of course. Good catch, thanks for pointing that out. –  Faiz Jan 22 '13 at 22:35

I am learning clisp, but it can work.

(defun append-all (x L)
    (flet (
        (append-item (alist) (append alist (list x))))
        (mapcar #'append-item L)))

(print (append-all '3 '((1) (2 1) (2))))
share|improve this answer

Your Answer


