As a simple matter of efficiency (which recursive functions are not exactly known for), and as a simple point of I guess you could say the "
elegance" of LISP... I think you'll find this variation even more robust, and efficient.
The replace2 function, in addition to that which the replace function already does, is to check that all arguments are non-Nil, and to ensure that the user does not attempt to replace a value within a list of lesser length (meaning that the fifth item of a list of three cannot be replaced).
My recent variation (posted above):
(defun replace
(aList position newItem
) (cons (car aList
) (replace
(cdr aList
) (- position
1) newItem
)) )
)
)
Current offering:
(defun replace2
(aList position newItem
) position
newItem
(subst newItem
(nth position aList
) aList
) )
)
Bench test results from VLIDE Console (100K iterations):
_$
REPLACE
_$
REPLACE2
_$
_$
(bench '
(replace replace2
) (list '
("FOO1" "FOO2" "FOO3") 2 "NEW") 100000)
REPLACE
Elapsed: 608
Average: 0.0061
REPLACE2
Elapsed: 562
Average: 0.0056
_$
Taking another hand-typed stab at the pseudo code syntax:
def replace(aList position newItem)
if and(aList, position, newItem, >=((1-(length(aList))), position)) then
subst(newItem, nth(position, aList), aList)
end;
Enjoy!