solinas10
solinas10

Reputation: 23

In Lisp, how do you add a given element to every list inside a given list?

Here's what I have so far:

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

Output:

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

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

Want:

((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.

Thanks

edit: fixed recursive call

Upvotes: 2

Views: 1132

Answers (4)

Melug
Melug

Reputation: 1031

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

Upvotes: 0

Rainer Joswig
Rainer Joswig

Reputation: 139401

(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
            list
            (circular-list (list item)))))

Upvotes: 2

Óscar López
Óscar López

Reputation: 236122

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.

Upvotes: 2

Faiz
Faiz

Reputation: 16265

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

Upvotes: 1

Related Questions