Solved- append a new atom upon finding specific atom

You have problems, and we're glad to hear them. Explain the problem, what you have tried, and where you got stuck.
Feel free to share a little info on yourself and the course.
Forum rules
Please respect your teacher's guidelines. Homework is a learning tool. If we just post answers, we aren't actually helping. When you post questions, be sure to show what you have tried or what you don't understand.
Post Reply
prashu421
Posts: 1
Joined: Sat Jan 06, 2018 11:39 pm

Solved- append a new atom upon finding specific atom

Post by prashu421 » Sat Jan 06, 2018 11:47 pm

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 -

Code: Select all

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

Code: Select all

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

David Mullen
Posts: 78
Joined: Mon Dec 01, 2014 12:29 pm
Contact:

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

Post by David Mullen » Wed Jan 10, 2018 3:51 pm

You're close—it just wants to be flipped inside out a little bit—the second clause should be like this:

Code: Select all

((EQ (car L) OLD) (cons OLD (cons NEW (appendConst OLD NEW (cdr L)))))

Post Reply