Search code examples
lispcommon-lisp

Doubling every item in list while limiting cons calls in Lisp


I have a function that doubles every item in a list:

(defun double (L)
   (cond
      ((atom L) nil)
      (t (cons (car L) (cons (car L ) (double (cdr L))))) ) )

(double '(a b c )) => (a a b b c c)

How could I accomplish the same result while dividing by 2 the number of times the function calls cons ? (i.e. in the previous example, it calls cons 6 times. How could I do it with 3 times only?)

Thanks!

Edit 2, after jkiiski's comments, seems like it works now:

(defun double2 (L)
   (cond
      ((atom L) nil)
      (t (setf
             (cdr L)
             (cons (car L ) (double2 (cdr L))))
         L) ) )


(double2 (list 'a 'b 'c)) => (a a b b c c) 

Solution

  • After jkiiski's comments, seems like it works now:

    (defun double2 (L)
       (cond
          ((atom L) nil)
          (t (setf
                 (cdr L)
                 (cons (car L ) (double2 (cdr L))))
             L) ) )
    
    (double2 (list 'a 'b 'c)) => (a a b b c c)