Reverse LISP list in place -


i write function reverses elements of list, should happen in place (that is, don't create new reversed list).

something like:

>> (setq l ' (a b c d)) ((a b c d) >> (rev l) (d c b a) >> l (d c b a) 

what flags should follow achieve this?

it's not difficult implement (ignoring fault cases). keys use (setf cdr) reuse given cons cell , not lose reference prior cdr.

(defun nreverse2 (list)   (recurse reving ((list list) (rslt '()))     (if (not (consp list))         rslt         (let ((rest (cdr list)))           (setf (cdr list) rslt)           (reving rest list)))))  (defmacro recurse (name args &rest body)   `(labels ((,name ,(mapcar #'car args) ,@body))      (,name ,@(mapcar #'cadr args)))) 

[edit] mentioned in comment, in-place (and w/o regard consing):

(defun reverse-in-place (l)   (let ((result l))     (recurse reving ((l l) (r (reverse l))       (cond ((not (consp l)) result)             (else (setf   (car l) (car r))                   (reving (cdr l) (cdr r)))))))  > (defvar l '(1 2 3)) > (reverse-in-place l)) (3 2 1) > l (3 2 1) 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -