Newsgroups: comp.lang.lisp
Path: cantaloupe.srv.cs.cmu.edu!bb3.andrew.cmu.edu!newsfeed.pitt.edu!gatech!swrinde!newsfeed.internetmci.com!EU.net!sun4nl!aie.nl!news
From: geert@michelv.aie.nl (Geert-Jan van Opdorp)
Subject: Re: Novice question -- inserting element in list
Sender: news@aie.nl (Usenet News)
Message-ID: <GEERT.96Feb6125137@michelv.aie.nl>
In-Reply-To: Gregory Santos's message of 6 Feb 1996 06:14:35 GMT
Date: Tue, 6 Feb 1996 11:51:36 GMT
Lines: 42
X-Nntp-Posting-Host: michelv.aie.nl
References: <4f6rkb$i11@watt.electriciti.com>
Organization: AI Engineering BV, Amsterdam, Netherlands

In article <4f6rkb$i11@watt.electriciti.com> Gregory Santos <timeline@electriciti.com> writes:


   [...]
> 
> (defun Insert-Node (theList node1 node2 &optional (a nil))
>    (let ((index (position node1 theList :test #'eq)))
                    ^^^^ 1st walk
>       (when index
>          (setq pos (if a (1+ index) index))
>          (setf theList
>                (nconc (subseq theList 0 pos)
                         ^^^^^ 2walk + copy!
>                   (list node2)
>                   (nthcdr pos theList))))))
                     ^^^^ 3 walk

1) Subseq makes a copy
2) The insertion spot is walked to 3 times. Lists
   are not vectors!

(defun Insert-Node (theList node1 node2 &optional (a nil))
   (let ((spot (member node1 theList :test #'eq)))
     (when spot
      (if a
          ;; destructively update cdr behind node1
          (push node2 (cdr spot))
          ;; destructively update both car & cdr;
          (push (shiftf (car spot) node2)
                (cdr spot))))))
                 

Geert-Jan


 

-- 
Geert-Jan van Opdorp
AI-Engineering
Amsterdam, The Netherlands
geert@aie.nl
