Search code examples
listduplicateslispcommon-lispcons

Is it possible to limit the number of calls to the cons function in the duplicate() function?


I wrote the function double() that duplicate the items in a list as follows:

(defun duplicate (l)
    (if (null l) nil
        (cons (car l) (cons (car l) ( duplicate (cdr l))))))

The duplicate() function make two calls to the CONS function for each item in a list:

Break 1 [2]> (trace cons)
;; Traçage de la fonction CONS.
(CONS)

Break 1 [2]> ( duplicate '(1 2 3))
1. Trace: (CONS '3 'NIL)
1. Trace: CONS ==> (3)
1. Trace: (CONS '3 '(3))
1. Trace: CONS ==> (3 3)
1. Trace: (CONS '2 '(3 3))
1. Trace: CONS ==> (2 3 3)
1. Trace: (CONS '2 '(2 3 3))
1. Trace: CONS ==> (2 2 3 3)
1. Trace: (CONS '1 '(2 2 3 3))
1. Trace: CONS ==> (1 2 2 3 3)
1. Trace: (CONS '1 '(1 2 2 3 3))
1. Trace: CONS ==> (1 1 2 2 3 3)
(1 1 2 2 3 3)

Is it possible to limit the number of calls to the CONS function to one per each list item?


Solution

  • NO, for the same reason you cannot fill a 10 liter bucket using 5 liters of water.

    A list of 10 elements requires 10 cons cells.