2

I have an implementation of a function called modify list shown below but it only works for top level lists.

(defun modify-list (old new a-list)
  (cond
   ((null a-list) nil)
   ((eql (car a-list) old) (cons new (modify-list old new (cdr a-list))))
   (T (cons (car a-list)(modify-list old new (cdr a-list))))))

CL-USER 16 : 6 > (modify-list 'a 'x '(p a d g c a)) (P X D G C X) <-- GOOD!

CL-USER 17 : 6 > (modify-list 'a 'x '(p a d (g a) c a)) (P X D (G A) C X) <----NOT GOOD!

can anyone help me make this function work on nested lists?

2 Answers 2

3

Why not working at an higher level? It would make the code simpler...

(defun modify (old new x)
  (cond
    ((eq x old) new)
    ((listp x)
     (mapcar (lambda (y) (modify old new y)) x))
    (t x)))

Basically instead of assuming x must be a list (actually a tree) you just return new if x is old, recursively map if it's a list or otherwise return x unchanged...

With this approach also (modify 'a 'x 'a) --> X (and that IMO seems right).

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

1 Comment

this is why I love stack overflow...always helpful THANKS
0

Here's an idea:

(defun modify-list (old new a-list)
  (cond ((null a-list) nil)
        ((not (listp (car a-list)))
         (if (eql (car a-list) old)
             (cons new (modify-list old new (cdr a-list)))
             (cons (car a-list) (modify-list old new (cdr a-list)))))
        (T (cons (modify-list old new (car a-list))
                 (modify-list old new (cdr a-list))))))

I don't have access to a LISP interpreter (anyone can verify the above procedure, please?), so you'll have to test it first!

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.