2

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

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

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: 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...
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).
1

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

1 Comment

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.