grge3113
grge3113

Reputation: 3

Lisp function that recursively adds elements to a list

I working on a lisp function that will accept two parameters, the second of which is a list. It will take the first parameter and add it after every element of the second parameter. This is as far as I got:

(defun rd(list n1 lis2)
  (rd ((n1) (cdr (lis2))))
  (cons (n1) (cons (car (lis2))))
  )

If the two parameters are 'aa and '(b c d f), the desired output should be: aa b aa c aa d aa f aa

Upvotes: 0

Views: 418

Answers (2)

PieCot
PieCot

Reputation: 3639

If you want insert the element after each head of the input list:

(defun f (a l)
    (cond
        ((null l) l)
        (T (cons (car l) (cons a (f a (cdr l)))))
    )
)
(format t "~a" (f 'aa '(1 2 3 3 4 5 5 6)))

(1 AA 2 AA 3 AA 3 AA 4 AA 5 AA 5 AA 6 AA)

In this case, if l is an empty list, the output will be NIL.

Otherwise if you want insert the element before every tail of the list (included the last tail, i.e. the empty list)

(defun f (a l)
    (cond
        ((null l) (list a))
        (T (cons a (cons (car l) (f a (cdr l)))))
    )
)

In this case:

(format t "~a" (f 'aa '(1 2 3 3 4 5 5 6)))

(AA 1 AA 2 AA 3 AA 3 AA 4 AA 5 AA 5 AA 6 AA)

If l is an empty list, the output will be the list (aa).

Upvotes: 0

Barmar
Barmar

Reputation: 782409

Don't put variables inside (), that's for calling functions.

If the function takes two parameters, the parameter list should just be (n1 lis2), no need for list before that.

You're not doing anything with the result of the recursive call. You need to combine it with n1 and the first element of lis2.

A recursive function has to check for the base case, otherwise it will recurse infinitely.

(defun rd (n1 lis2)
  (if (null lis2)
      (list n1) ;; Add n1 at the end
      (list* n1 (car lis2) (rd n1 (cdr lis2))))) ;; put n1 before every element

(rd 'aa '(1 2 3 4 5)) ;; => (aa 1 aa 2 aa 3 aa 4 aa 5 aa)

Upvotes: 3

Related Questions