This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

Solved- append a new atom upon finding specific atom

2 posts · 3673 views

I've recently started working on LISP as part of my course.
I am trying to add a new atom after every search atom in the list, my code is as below -
(defun appendConst (OLD NEW L)
   (cond
     ((null L) ())
     ((EQ (car L) OLD) (cons OLD (cons NEW (cdr L))))
     (T (cons (car L) (appendConst OLD NEW (cdr L))))
))
This is working fine, but only adding the required atom in first occurrence. Please check example below -
Input: (appendConst 'a 'd '(a c e a m k))
Ouput: (A D C E A M K)
Required Output: (A D C E A D M K)

I tried calling the function recursively, but I can see that it doesn't work, as the no. of arguments are not properly being passed.
(defun appendConst (OLD NEW L)
       (cond
         ((null L) ())
         ((EQ (car L) OLD) (appendConst (cons OLD (cons NEW (cdr L))))  )
         (T (cons (car L) (appendConst OLD NEW (cdr L))))
    ))
Thanks.

Re: Solved- append a new atom upon finding specific atom

You're close—it just wants to be flipped inside out a little bit—the second clause should be like this:
((EQ (car L) OLD) (cons OLD (cons NEW (appendConst OLD NEW (cdr L)))))