-1

I try to reverse a list, i can't use the function "nreverse"

I try :

(defun dolist-reverse (l)
  (let ((new-list (make-list (length l))))
    (dolist (x l new-list)
      (setf new-list (cons x new-list)))))

But the result is :

CL-USER> (dolist-reverse '(1 2 3))

(3 2 1 NIL NIL NIL)

How can i do ? (i need to use dolist)

EDIT :

Finally fix my problem :

(defun dolist-reverse (l)
  (let ((new-list))
    (dolist (x l new-list)
      (setf new-list (cons x new-list)))))
Saro Taşciyan
  • 5,210
  • 5
  • 31
  • 50
mpgn
  • 7,121
  • 9
  • 67
  • 100
  • 1
    If you found a solution to your problem, then you should post it as an answer with an explanation and mark it accepted. – Joshua Taylor Dec 13 '13 at 04:07

2 Answers2

3
CL-USER 11 > (defun dolist-reverse (list &aux (reverse-list nil))
               (dolist (element list reverse-list)
                 (push element reverse-list)))
DOLIST-REVERSE

CL-USER 12 > (dolist-reverse '(1 2 3))
(3 2 1)
Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
-1

This one makes same thing, without changing argument to the procedure;

 (defun my-reverse (l)
     (if (null l) nil
       (append
         (my-reverse (cdr l))
         (list (car l)))))
sçuçu
  • 2,960
  • 2
  • 33
  • 60
  • martialp, why do you need dolist? – sçuçu Dec 13 '13 at 04:12
  • why append is a very bad idea? – sçuçu Dec 13 '13 at 06:34
  • and the reason i did the above to both to show existence of an algorithm without iterative constructs, and the simplicity of the idea behind expressing reverse of a list as being reverse of rest of the list glued to first of the list. – sçuçu Dec 13 '13 at 06:47
  • 2
    @user97457 good; :) more than that, you can do it without `append` too, only `cons`. [Here's a link](http://stackoverflow.com/q/19529829/849891) - or try solve it first by yourself.. -- repeated append at the end is bad because it copies its first argument. your algorithm is quadratic (at least). So it's only a fun toy. :) – Will Ness Dec 13 '13 at 08:31