3

I have the following structure:

'((a (1 2 3 4))
  (b (1 2))
  (c (1 3 4 5))

I want to return a new list that's similar, but that has a 7 inserted after each 2:

'((a (1 2 7 3 4))
  (b (1 2 7))
  (c (1 3 4 5))

How can I do this?

2
  • You do not want to mutate a quoted list. Also, mapcar is non-destructive, i.e., it does not mutate its arguments.
    – sds
    Sep 2 '20 at 18:02
  • @sds maybe I was unable to explain myself better, due to my lack of Lisp expertise I guess, but I'm okay if the result is a new list.
    – shackra
    Sep 2 '20 at 18:04
4

You need a nested mapcar and mapcan:

(mapcar
 (lambda (l)
   (list (car l)
         (mapcan
          (lambda (x)
            (if (= x 2)
                (list x 7)
              (list x)))
          (cadr l))))
 '((a (1 2 3 4))
   (b (1 2))
   (c (1 3 4 5))))
==> ((a (1 2 7 3 4)) (b (1 2 7)) (c (1 3 4 5)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.