Reputation: 149
I want to insert an element next to the last element of the list, but I only know how to insert an element next to the first element of the list, can someone help me further? Example : (insert '5 '(1 3 2 7 8 9)) should output => (1 3 2 7 8 5 9)
(defun insert (item list)
(cons (first list)
(cons item
(rest list))))
//when I do (insert '5 '(1 3 2 7 8 9)) I get (1 5 3 2 7 8 9)
Upvotes: 1
Views: 2081
Reputation: 48745
Lists are singly linked lists so only add to the front is possible without having to copy parts of the list. your attempt makes a copy of the first pair, the add your pair as the second element then share the rest of the original list with the argument.
In order to add as the last element you need to do this until list
is empty and then return a list with the one element. None of the cons will be in common. So:
(insert 'x '()) ; ==> (list 'x)
(insert 'x '(1)) ; ==> (cons '1 (insert 'x (cdr '(1))))
Of course this can be done with append
. Laziness is rewarded in programming:
(defun insert-last (item list)
(append list (list item)))
Know that if you have a recursive function or an iteration where you add like this for many elements depending on the arguments you are making a very bad algorithm. It is much better to either use loop
to collect
to the end or to make the list backwards and in the last step reverse it. Then you'll get n or 2n passes through the data instead of n^2.
Upvotes: 4