Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!think.com!barmar From: barmar@think.com (Barry Margolin) Newsgroups: comp.lang.lisp Subject: Re: Destructive Operations Message-ID: <1991Apr25.052624.14541@Think.COM> Date: 25 Apr 91 05:26:24 GMT References: <1351@ai.cs.utexas.edu> Sender: news@Think.COM Organization: Thinking Machines Corporation, Cambridge MA, USA Lines: 50 In article <1351@ai.cs.utexas.edu> gideon@cs.utexas.edu (Timothy Tin-Wai Chan) writes: > I've been programming in LISP for quite some time, but I've always >gotten into buggy situations due to my misuse of destructive operations. >In fact, I can't even tell if I've used a destructive operation or not. In Common Lisp, the names of most destructive functions have the prefix "N" (sorry, I don't recall the derivation of this). The exceptions I can think of are SORT, DELETE and its variants (they are destructive versions of REMOVE), RPLACA/D, and SETF of any list accessors. >Does somebody have a general rule on how to watch out for misuse of >destructive operations? Or do you know of a reference to books talking >about destructive operations in LISP? There are two common problems encountered when using destructive operations. 1. Forgetting to store the result back. Even though the list is modified in place, it is still necessary to store the result back into the original location, e.g. (setq foo (delete 'x foo)) This is necessary because X might be the first element of the list, so DELETE could just return (CDR FOO), without actually modifying anything (it can't store the result itself because of Lisp's call-by-value semantics). If the original list was stored in multiple places, you may need to store it back in all of them, e.g. (setq bar foo) ... (setq foo (delete 'x foo)) (setq bar foo) 2. Sharing structure that gets modified. (setq bar (cdr foo)) ... (setq foo (sort foo #'<)) ;;; now it's not safe to use BAR It's generally best not to perform destructive operations on lists that are shared in this way. You can use COPY-LIST or COPY-TREE, and then it will be safe to modify the structure. -- Barry Margolin, Thinking Machines Corp. barmar@think.com {uunet,harvard}!think!barmar