Search code examples
lispelisp

LISP - atom after every occurrence of search atom


I am trying to add a new atom after the search atom in the list.

when I try to call the function appendConst recursively, I am getting the below error -

[1]> (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))))
    ))
APPENDCONST
[2]> (appendConst 'a 'd '(a c d e a m k))

*** - EVAL/APPLY: Too few arguments (1 instead of at least 3) given to APPENDCONST
The following restarts are available:
ABORT          :R1      Abort main loop
Break 1 [3]> 

Here, using my input, after every occurrence of 'a' I want to add a 'd' in the whole list given.

I am new to this, how to call the function recursively here?

TIA.


Solution

  • Your first recursive call (where you add NEW) does in fact have only the one argument that the error says it does. Just adding the missing OLD and NEW won’t work, since the recursive call would find OLD again. So just do the consing outside the call as in your other case:

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

    Note that neither case is tail-recursive: to avoid stack usage proportional to the length of the list, you’d have to modify the list in place or do something more complicated like passing the head and the tail of the new list when recursing.