0

I'm trying to increment elements in a list by creating a new list to which I would append incremented elements of an old list in dolist loop.

First I tried this and it didn't work:

(defun increment-list(old-list)
    (setq new-list (list))
    (when (listp old-list)
        (dolist (x old-list) (append new-list (+ x 1)))
        (print new-list)
    )
)

Then I thought that maybe list can only be appended with another list, so I changed dolist to look like this:

(dolist (x old-list) (append new-list (list (+ x 1))))

Both solutions left gave the same result - new-list was NIL.

Currently, I'm using push, but it makes a reversed list. I could reverse it again, but it seems to be an unnecessary complication.

I have also found other solutions which I could use. However, I'm eager to find out why append doesn't work here because according to this answer it should.

Community
  • 1
  • 1
John Mellor
  • 171
  • 1
  • 1
  • 8
  • 1
    APPEND doesn't modify a list. It returns a new one. In your case, you'd do `(setq new-list (append new-list (+ x 1)))`. This requires traversing the entire `new-list` each time though. It would be more efficient to collect the list in reverse order and reverse it at the end. In fact, the common way to do that would be `(let ((new-list '())) (dolist (x list (nreverse new-list)) (push (1+ x) new-list)))`. (Note the third element in the argument list to `dolist`, and you may want to look at the function `1+`. – Joshua Taylor Oct 25 '16 at 16:41
  • It works, I wasn't aware of the possibility of using third argument in `dolist`. Thank you very much. – John Mellor Oct 25 '16 at 17:01
  • Are you aware of the [`mapcar`](http://www.lispworks.com/documentation/HyperSpec/Body/f_mapc_.htm) function that can reduce your function body to `(mapcar #'1+ old-list)` – Terje D. Oct 25 '16 at 18:40
  • Yes, I'm aware of that, but like I said, I wanted to do this using `dolist`. – John Mellor Oct 26 '16 at 13:19

0 Answers0