Subject: Re: How to reverse a list...
From: Erik Naggum <erik@naggum.net>
Date: Tue, 04 Dec 2001 00:31:41 GMT
Newsgroups: comp.lang.lisp
Message-ID: <3216414699382977@naggum.net>

* "Frederic Brunel" <brunel@mail.dotcom.fr>
| In my opinion, an elegant and typical functional way to do this is to use
| an auxiliary function taking a second argument to accumulate the result:
| 
| (defun reverse-aux (l acc)
|   (if (nilp l)
|       acc
|       (reverse-aux (cdr l)
|                    (append (list (car l)) acc))))
| 
| (defun my-reverse (l)
|   (reverse-aux l '()))
| 
| You could use the `label' special-form to declare the `reverse-aux'
| function as a local function within the `my-reverse' function or set the
| `acc' argument as an optional one!

  That would probably be elegant only in Scheme.

  Please note that (append (list elt) list) is functionally identical to
  (cons elt list), except that it copies and wastes the first argument.

  This is another way to do it:

(defun reverse-list (list)
  (do ((list list (cdr list))
       (rev () (cons (car list) rev)))
      ((endp list) rev)))

///
-- 
  The past is not more important than the future, despite what your culture
  has taught you.  Your future observations, conclusions, and beliefs are
  more important to you than those in your past ever will be.  The world is
  changing so fast the balance between the past and the future has shifted.