home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Information / Languages / Lisp / lisp-faq⁄part3 < prev    next >
Encoding:
Text File  |  1994-12-08  |  36.1 KB  |  719 lines  |  [TEXT/R*ch]

  1. Path: bloom-beacon.mit.edu!uhog.mit.edu!nntp.club.cc.cmu.edu!cantaloupe.srv.cs.cmu.edu!mkant
  2. From: mkant+@cs.cmu.edu (Mark Kantrowitz)
  3. Newsgroups: comp.lang.lisp,news.answers,comp.answers
  4. Subject: FAQ: Lisp Frequently Asked Questions 3/7 [Monthly posting]
  5. Supersedes: <LISP_3_782031621@CS.CMU.EDU>
  6. Followup-To: poster
  7. Date: 13 Nov 1994 08:01:13 GMT
  8. Organization: Carnegie-Mellon University, School of Computer Science
  9. Lines: 789
  10. Approved: news-answers-request@MIT.Edu
  11. Distribution: world
  12. Expires: 25 Dec 1994 08:00:25 GMT
  13. Message-ID: <LISP_3_784713625@CS.CMU.EDU>
  14. References: <LISP_2_784713625@CS.CMU.EDU>
  15. Reply-To: ai+lisp-faq@cs.cmu.edu
  16. NNTP-Posting-Host: glinda.oz.cs.cmu.edu
  17. Summary: Common Pitfalls
  18. Xref: bloom-beacon.mit.edu comp.lang.lisp:7453 news.answers:29282 comp.answers:8317
  19.  
  20. Archive-name: lisp-faq/part3
  21. Last-Modified: Tue Sep 13 18:05:47 1994 by Mark Kantrowitz
  22. Version: 1.50
  23. Maintainer: Mark Kantrowitz and Barry Margolin <ai+lisp-faq@cs.cmu.edu>
  24. URL: http://www.cs.cmu.edu:8001/Web/Groups/AI/html/faqs/lang/lisp/top.html
  25. Size: 36400 bytes, 797 lines
  26.  
  27. ;;; ****************************************************************
  28. ;;; Answers to Frequently Asked Questions about Lisp ***************
  29. ;;; ****************************************************************
  30. ;;; Written by Mark Kantrowitz and Barry Margolin
  31. ;;; lisp_3.faq
  32.  
  33. This post contains Part 3 of the Lisp FAQ.
  34.  
  35. If you think of questions that are appropriate for this FAQ, or would
  36. like to improve an answer, please send email to us at ai+lisp-faq@cs.cmu.edu.
  37.  
  38. This section contains a list of common pitfalls. Pitfalls are aspects
  39. of Common Lisp which are non-obvious to new programmers and often
  40. seasoned programmers as well.
  41.  
  42. Common Pitfalls (Part 3):
  43.  
  44.   [3-0]  Why does (READ-FROM-STRING "foobar" :START 3) return FOOBAR
  45.          instead of BAR?  
  46.   [3-1]  Why can't it deduce from (READ-FROM-STRING "foobar" :START 3)
  47.          that the intent is to specify the START keyword parameter
  48.          rather than the EOF-ERROR-P and EOF-VALUE optional parameters?   
  49.   [3-2]  Why can't I apply #'AND and #'OR?
  50.   [3-3]  I used a destructive function (e.g. DELETE, SORT), but it
  51.          didn't seem to work.  Why? 
  52.   [3-4]  After I NREVERSE a list, it's only one element long.  After I
  53.          SORT a list, it's missing things.  What happened? 
  54.   [3-5]  Why does (READ-LINE) return "" immediately instead of waiting
  55.          for me to type a line?  
  56.   [3-6]  I typed a form to the read-eval-print loop, but nothing happened. Why?
  57.   [3-7]  DEFMACRO doesn't seem to work.
  58.          When I compile my file, LISP warns me that my macros are undefined
  59.          functions, or complains "Attempt to call <function> which is 
  60.          defined as a macro.
  61.   [3-8]  Name conflict errors are driving me crazy! (EXPORT, packages)
  62.   [3-9]  Closures don't seem to work properly when referring to the
  63.          iteration variable in DOLIST, DOTIMES, DO and LOOP.
  64.   [3-10] What is the difference between FUNCALL and APPLY?
  65.   [3-11] Miscellaneous things to consider when debugging code.
  66.   [3-12] When is it right to use EVAL?
  67.   [3-13] Why does my program's behavior change each time I use it?
  68.   [3-14] When producing formatted output in Lisp, where should you put the
  69.          newlines (e.g., before or after the line, FRESH-LINE vs TERPRI,
  70.          ~& vs ~% in FORMAT)?
  71.   [3-15] I'm using DO to do some iteration, but it doesn't terminate. 
  72.   [3-16] My program works when interpreted but not when compiled!
  73.  
  74. Search for \[#\] to get to question number # quickly.
  75.  
  76. ----------------------------------------------------------------
  77. Subject: [3-0] Why does (READ-FROM-STRING "foobar" :START 3) return FOOBAR 
  78.                instead of BAR?
  79.  
  80. READ-FROM-STRING is one of the rare functions that takes both &OPTIONAL and
  81. &KEY arguments:
  82.  
  83.        READ-FROM-STRING string &OPTIONAL eof-error-p eof-value 
  84.                                &KEY :start :end :preserve-whitespace
  85.  
  86. When a function takes both types of arguments, all the optional
  87. arguments must be specified explicitly before any of the keyword
  88. arguments may be specified.  In the example above, :START becomes the
  89. value of the optional EOF-ERROR-P parameter and 3 is the value of the
  90. optional EOF-VALUE parameter.
  91.      
  92. To get the desired result, you should use
  93.    (READ-FROM-STRING "foobar" t nil :START 3)
  94. If you need to understand and use the optional arguments, please refer
  95. to CLTL2 under READ-FROM-STRING, otherwise, this will behave as
  96. desired for most purposes.
  97.  
  98. ----------------------------------------------------------------
  99. Subject: [3-1] Why can't it deduce from (READ-FROM-STRING "foobar" :START 3) 
  100.       that the intent is to specify the START keyword parameter rather than
  101.       the EOF-ERROR-P and EOF-VALUE optional parameters?
  102.  
  103. In Common Lisp, keyword symbols are first-class data objects.  Therefore,
  104. they are perfectly valid values for optional parameters to functions.
  105. There are only four functions in Common Lisp that have both optional and
  106. keyword parameters (they are PARSE-NAMESTRING, READ-FROM-STRING,
  107. WRITE-LINE, and WRITE-STRING), so it's probably not worth adding a
  108. nonorthogonal kludge to the language just to make these functions slightly
  109. less confusing; unfortunately, it's also not worth an incompatible change
  110. to the language to redefine those functions to use only keyword arguments.
  111.      
  112. ----------------------------------------------------------------
  113. Subject: [3-2] Why can't I apply #'AND and #'OR?
  114.  
  115. Here's the simple, but not necessarily satisfying, answer: AND and OR are
  116. macros, not functions; APPLY and FUNCALL can only be used to invoke
  117. functions, not macros and special operators.
  118.  
  119. OK, so what's the *real* reason?  The reason that AND and OR are macros
  120. rather than functions is because they implement control structure in
  121. addition to computing a boolean value.  They evaluate their subforms
  122. sequentially from left/top to right/bottom, and stop evaluating subforms as
  123. soon as the result can be determined (in the case of AND, as soon as a
  124. subform returns NIL; in the case of OR, as soon as one returns non-NIL);
  125. this is referred to as "short circuiting" in computer language parlance.
  126. APPLY and FUNCALL, however, are ordinary functions; therefore, their
  127. arguments are evaluated automatically, before they are called.  Thus, were
  128. APPLY able to be used with #'AND, the short-circuiting would be defeated.
  129.  
  130. Perhaps you don't really care about the short-circuiting, and simply want
  131. the functional, boolean interpretation.  While this may be a reasonable
  132. interpretation of trying to apply AND or OR, it doesn't generalize to other
  133. macros well, so there's no obvious way to have the Lisp system "do the
  134. right thing" when trying to apply macros.  The only function associated
  135. with a macro is its expander function; this function accepts and returns
  136. and form, so it cannot be used to compute the value.
  137.  
  138. The Common Lisp functions EVERY and SOME can be used to get the
  139. functionality you intend when trying to apply #'AND and #'OR.  For
  140. instance, the erroneous form:
  141.  
  142.    (apply #'and *list*)
  143.  
  144. can be translated to the correct form:
  145.  
  146.    (every #'identity *list*)
  147.  
  148. ----------------------------------------------------------------
  149. Subject: [3-3] I used a destructive function (e.g. DELETE, SORT), but 
  150.                it didn't seem to work.  Why?
  151.  
  152. I assume you mean that it didn't seem to modify the original list.  There
  153. are several possible reasons for this.  First, many destructive functions
  154. are not *required* to modify their input argument, merely *allowed* to; in
  155. some cases, the implementation may determine that it is more efficient to
  156. construct a new result than to modify the original (this may happen in Lisp
  157. systems that use "CDR coding", where RPLACD may have to turn a CDR-NEXT or
  158. CDR-NIL cell into a CDR-NORMAL cell), or the implementor may simply not
  159. have gotten around to implementing the destructive version in a truly
  160. destructive manner.  Another possibility is that the nature of the change
  161. that was made involves removing elements from the front of a list; in this
  162. case, the function can simply return the appropriate tail of the list,
  163. without actually modifying the list. And example of this is:
  164.      
  165.    (setq *a* (list 3 2 1))
  166.    (delete 3 *a*) => (2 1)
  167.    *a* => (3 2 1)
  168.  
  169. Similarly, when one sorts a list, SORT may destructively rearrange the
  170. pointers (cons cells) that make up the list. SORT then returns the cons
  171. cell that now heads the list; the original cons cell could be anywhere in
  172. the list. The value of any variable that contained the original head of the
  173. list hasn't changed, but the contents of that cons cell have changed
  174. because SORT is a destructive function:
  175.  
  176.    (setq *a* (list 2 1 3))
  177.    (sort *a* #'<) => (1 2 3)
  178.    *a* => (2 3)     
  179.  
  180. In both cases, the remedy is the same: store the result of the
  181. function back into the place whence the original value came, e.g.
  182.  
  183.    (setq *a* (delete 3 *a*))
  184.    *a* => (2 1)
  185.  
  186. Why don't the destructive functions do this automatically?  Recall
  187. that they are just ordinary functions, and all Lisp functions are
  188. called by value. They see the value of the argument, not the argument
  189. itself. Therefore, these functions do not know where the lists they
  190. are given came from; they are simply passed the cons cell that
  191. represents the head of the list. Their only obligation is to return
  192. the new cons cell that represents the head of the list. Thus
  193. "destructive" just means that the function may munge the list by
  194. modifying the pointers in the cars and cdrs of the list's cons cells.
  195. This can be more efficient, if one doesn't care whether the original
  196. list gets trashed or not.
  197.  
  198. One thing to be careful about when doing this (storing the result back
  199. into the original location) is that the original list might be
  200. referenced from multiple places, and all of these places may need to
  201. be updated.  For instance:
  202.  
  203.    (setq *a* (list 3 2 1))
  204.    (setq *b* *a*)
  205.    (setq *a* (delete 3 *a*))
  206.    *a* => (2 1)
  207.    *b* => (3 2 1) ; *B* doesn't "see" the change
  208.    (setq *a* (delete 1 *a*))
  209.    *a* => (2)
  210.    *b* => (3 2) ; *B* sees the change this time, though
  211.  
  212. One may argue that destructive functions could do what you expect by
  213. rearranging the CARs of the list, shifting things up if the first element
  214. is being deleted, as they are likely to do if the argument is a vector
  215. rather than a list.  In many cases they could do this, although it would
  216. clearly be slower.  However, there is one case where this is not possible:
  217. when the argument or value is NIL, and the value or argument, respectively,
  218. is not.  It's not possible to transform the object referenced from the
  219. original cell from one data type to another, so the result must be stored
  220. back.  Here are some examples:
  221.  
  222.    (setq *a* (list 3 2 1))
  223.    (delete-if #'numberp *a) => NIL
  224.    *a* => (3 2 1)
  225.    (setq *a* nil *b* '(1 2 3))
  226.    (nconc *a* *b*) => (1 2 3)
  227.    *a* => NIL
  228.  
  229. The names of most destructure functions (except for sort, delete,
  230. rplaca, rplacd, and setf of accessor functions) have the prefix N.
  231.  
  232. In summary, the two common problems to watch out for when using
  233. destructive functions are:
  234.  
  235.    1. Forgetting to store the result back. Even though the list
  236.       is modified in place, it is still necessary to store the
  237.       result of the function back into the original location, e.g.,
  238.            (setq foo (delete 'x foo))
  239.  
  240.       If the original list was stored in multiple places, you may
  241.       need to store it back in all of them, e.g.
  242.            (setq bar foo)
  243.            ...
  244.            (setq foo (delete 'x foo))
  245.            (setq bar foo)
  246.  
  247.    2. Sharing structure that gets modified. If it is important
  248.       to preserve the shared structure, then you should either
  249.       use a nondestructive operation or copy the structure first
  250.       using COPY-LIST or COPY-TREE.
  251.            (setq bar (cdr foo))
  252.            ...
  253.            (setq foo (sort foo #'<))
  254.            ;;; now it's not safe to use BAR
  255.  
  256. Note that even nondestructive functions, such as REMOVE, and UNION,
  257. can return a result which shares structure with an argument. 
  258. Nondestructive functions don't necessarily copy their arguments; they
  259. just don't modify them.
  260.      
  261. ----------------------------------------------------------------
  262. Subject: [3-4] After I NREVERSE a list, it's only one element long.  
  263.                After I SORT a list, it's missing things.  What happened?
  264.  
  265. These are particular cases of the previous question.  Many NREVERSE and
  266. SORT implementations operate by rechaining all the CDR links in the list's
  267. backbone, rather than by replacing the CARs.  In the case of NREVERSE, this
  268. means that the cons cell that was originally first in the list becomes the
  269. last one.  As in the last question, the solution is to store the result
  270. back into the original location.
  271.      
  272. ----------------------------------------------------------------
  273. Subject: [3-5] Why does (READ-LINE) return "" immediately instead of 
  274.                waiting for me to type a line?
  275.  
  276. Many Lisp implementations on line-buffered systems do not discard the
  277. newline that the user must type after the last right parenthesis in order
  278. for the line to be transmitted from the OS to Lisp.  Lisp's READ function
  279. returns immediately after seeing the matching ")" in the stream.  When
  280. READLINE is called, it sees the next character in the stream, which is a
  281. newline, so it returns an empty line.  If you were to type "(read-line)This
  282. is a test" the result would be "This is a test".
  283.  
  284. The simplest solution is to use (PROGN (CLEAR-INPUT) (READ-LINE)).  This
  285. discards the buffered newline before reading the input.  However, it would
  286. also discard any other buffered input, as in the "This is a test" example
  287. above; some implementation also flush the OS's input buffers, so typeahead
  288. might be thrown away.
  289.  
  290. ----------------------------------------------------------------
  291. Subject: [3-6] I typed a form to the read-eval-print loop, but 
  292.                nothing happened. Why?
  293.  
  294. There's not much to go on here, but a common reason is that you haven't
  295. actually typed a complete form.  You may have typed a doublequote, vertical
  296. bar, "#|" comment beginning, or left parenthesis that you never matched
  297. with another doublequote, vertical bar, "|#", or right parenthesis,
  298. respectively.  Try typing a few right parentheses followed by Return.
  299.  
  300. ----------------------------------------------------------------
  301. Subject: [3-7]  DEFMACRO doesn't seem to work. 
  302.                 When I compile my file, LISP warns me that my macros
  303.                 are undefined functions, or complains 
  304.                   "Attempt to call <function> which is defined as a macro."
  305.  
  306. When you evaluate a DEFMACRO form or proclaim a function INLINE, it
  307. doesn't go back and update code that was compiled under the old
  308. definition. When redefining a macro, be sure to recompile any
  309. functions that use the macro. Also be sure that the macros used in a
  310. file are defined before any forms in the same file that use them.
  311.  
  312. Certain forms, including LOAD, SET-MACRO-CHARACTER, and
  313. REQUIRE, are not normally evaluated at compile time. Common Lisp
  314. requires that macros defined in a file be used when compiling later
  315. forms in the file. If a Lisp doesn't follow the standard, it may be
  316. necessary to wrap an EVAL-WHEN form around the macro definition.
  317.  
  318. Most often the "macro was previously called as a function" problem
  319. occurs when files were compiled/loaded in the wrong order. For
  320. example, developers may add the definition to one file, but use it in
  321. a file which is compiled/loaded before the definition. To work around
  322. this problem, one can either fix the modularization of the system, or
  323. manually recompile the files containing the forward references to macros.
  324.  
  325. Also, if your macro calls functions at macroexpand time, those functions
  326. may need to be in an EVAL-WHEN. For example,
  327.  
  328.     (defun some-function (x)
  329.       x)
  330.  
  331.     (defmacro some-macro (y)
  332.       (let ((z (some-function y)))
  333.         `(print ',z)))
  334.  
  335. If the macros are defined in a file you require, make sure your
  336. require or load statement is in an appropriate EVAL-WHEN. Many people
  337. avoid all this nonsense by making sure to load all their files before
  338. compiling them, or use a system facility (or just a script file) that
  339. loads each file before compiling the next file in the system.
  340.  
  341. ----------------------------------------------------------------
  342. Subject: [3-8]  Name conflict errors are driving me crazy! (EXPORT, packages)
  343.  
  344. If a package tries to export a symbol that's already defined, it will
  345. report an error. You probably tried to use a function only to discover
  346. that you'd forgotten to load its file. The failed attempt at using the
  347. function caused its symbol to be interned. So now, when you try to
  348. load the file, you get a conflict. Unfortunately, understanding and
  349. correcting the code which caused the export problem doesn't make those
  350. nasty error messages go away. That symbol is still interned where it
  351. shouldn't be. Use unintern to remove the symbol from a package before
  352. reloading the file. Also, when giving arguments to REQUIRE or package
  353. functions, use strings or keywords, not symbols: (find-package "FOO"),
  354. (find-package :foo). 
  355.  
  356. A sometimes useful technique is to rename (or delete) a package
  357. that is "too messed up".  Then you can reload the relevant files
  358. into a "clean" package.
  359.  
  360. ----------------------------------------------------------------
  361. Subject: [3-9]  Closures don't seem to work properly when referring to the
  362.                 iteration variable in DOLIST, DOTIMES, DO and LOOP.
  363.  
  364. DOTIMES, DOLIST, DO and LOOP all use assignment instead of binding to
  365. update the value of the iteration variables. So something like
  366.    
  367.    (let ((l nil))
  368.      (dotimes (n 10)
  369.        (push #'(lambda () n)
  370.          l)))
  371.  
  372. will produce 10 closures over the same value of the variable N. To
  373. avoid this problem, you'll need to create a new binding after each
  374. assignment: 
  375.  
  376.    (let ((l nil))
  377.      (dotimes (n 10)
  378.     (let ((n n))
  379.       (push #'(lambda () n)
  380.         l))))
  381.  
  382. Then each closure will be over a new binding of n.
  383.  
  384. This is one reason why programmers who use closures prefer MAPC and
  385. MAPCAR to DOLIST.
  386.  
  387. ----------------------------------------------------------------
  388. Subject: [3-10] What is the difference between FUNCALL and APPLY?
  389.  
  390. FUNCALL is useful when the programmer knows the length of the argument
  391. list, but the function to call is either computed or provided as a
  392. parameter.  For instance, a simple implementation of MEMBER-IF (with
  393. none of the fancy options) could be written as:
  394.  
  395. (defun member-if (predicate list)
  396.   (do ((tail list (cdr tail)))
  397.       ((null tail))
  398.    (when (funcall predicate (car tail))
  399.      (return-from member-if tail))))
  400.  
  401. The programmer is invoking a caller-supplied function with a known
  402. argument list.
  403.  
  404. APPLY is needed when the argument list itself is supplied or computed.
  405. Its last argument must be a list, and the elements of this list become
  406. individual arguments to the function.  This frequently occurs when a
  407. function takes keyword options that will be passed on to some other
  408. function, perhaps with application-specific defaults inserted.  For
  409. instance:
  410.  
  411. (defun open-for-output (pathname &rest open-options)
  412.   (apply #'open pathname :direction :output open-options))
  413.  
  414. FUNCALL could actually have been defined using APPLY:
  415.  
  416. (defun funcall (function &rest arguments)
  417.   (apply function arguments))
  418.  
  419. ----------------------------------------------------------------
  420. Subject: [3-11] Miscellaneous things to consider when debugging code.
  421.  
  422. This question lists a variety of problems to watch out for when
  423. debugging code. This is sort of a catch-all question for problems too
  424. small to merit a question of their own. See also question [1-3] for
  425. some other common problems.
  426.  
  427. Functions:
  428.  
  429.   * (flet ((f ...)) (eq #'f #'f)) can return false.
  430.  
  431.   * The function LIST-LENGTH is not a faster, list-specific version
  432.     of the sequence function LENGTH.  It is list-specific, but it's
  433.     slower than LENGTH because it can handle circular lists.
  434.  
  435.   * Don't confuse the use of LISTP and CONSP. CONSP tests for the
  436.     presence of a cons cell, but will return NIL when called on NIL.
  437.     LISTP could be defined as (defun listp (x) (or (null x) (consp x))).
  438.  
  439.   * Use the right test for equality: 
  440.         EQ      tests if the objects are identical -- numbers with the
  441.                 same value need not be EQ, nor are two similar lists
  442.                 necessarily EQ. Similarly for characters and strings.
  443.                 For instance, (let ((x 1)) (eq x x)) is not guaranteed
  444.                 to return T.
  445.         EQL     Like EQ, but is also true if the arguments are numbers
  446.                 of the same type with the same value or character objects
  447.                 representing the same character. (eql -0.0 0.0) is not
  448.                 guaranteed to return T.
  449.         EQUAL   Tests if the arguments are structurally isomorphic, using
  450.                 EQUAL to compare components that are conses, bit-vectors, 
  451.                 strings or pathnames, and EQ for all other data objects
  452.                 (except for numbers and characters, which are compared
  453.                 using EQL). Except for strings and bit-vectors, arrays
  454.                 are EQUAL only if they are EQ.
  455.         EQUALP  Like EQUAL, but ignores type differences when comparing 
  456.                 numbers and case differences when comparing characters.
  457.         =       Compares the values of two numbers even if they are of
  458.                 different types.
  459.         CHAR=   Case-sensitive comparison of characters.
  460.         CHAR-EQUAL      Case-insensitive comparison of characters.
  461.         STRING= Compares two strings, checking if they are identical.
  462.                 It is case sensitive.
  463.         STRING-EQUAL  Like STRING=, but case-insensitive.
  464.  
  465.   * Some destructive functions that you think would modify CDRs might
  466.     modify CARs instead.  (E.g., NREVERSE.)
  467.  
  468.   * READ-FROM-STRING has some optional arguments before the
  469.     keyword parameters.  If you want to supply some keyword
  470.     arguments, you have to give all of the optional ones too.
  471.  
  472.   * If you use the function READ-FROM-STRING, you should probably bind
  473.     *READ-EVAL* to NIL. Otherwise an unscrupulous user could cause a
  474.     lot of damage by entering 
  475.         #.(shell "cd; rm -R *")
  476.     at a prompt.
  477.  
  478.   * Only functional objects can be funcalled in CLtL2, so a lambda
  479.     expression '(lambda (..) ..) is no longer suitable. Use
  480.     #'(lambda (..) ..) instead. If you must use '(lambda (..) ..),
  481.     coerce it to type FUNCTION first using COERCE.
  482.  
  483. Methods:
  484.  
  485.   * PRINT-OBJECT methods can make good code look buggy. If there is a
  486.     problem with the PRINT-OBJECT methods for one of your classes, it
  487.     could make it seem as though there were a problem with the object.
  488.     It can be very annoying to go chasing through your code looking for
  489.     the cause of the wrong value, when the culprit is just a bad
  490.     PRINT-OBJECT method.
  491.  
  492. Initialization:
  493.  
  494.   * Don't count on array elements being initialized to NIL, if you don't
  495.     specify an :initial-element argument to MAKE-ARRAY. For example,
  496.          (make-array 10) => #(0 0 0 0 0 0 0 0 0 0)
  497.  
  498. Iteration vs closures:
  499.  
  500.   * DO and DO* update the iteration variables by assignment; DOLIST and
  501.     DOTIMES are allowed to use assignment (rather than a new binding).
  502.     (All CLtL1 says of DOLIST and DOTIMES is that the variable "is
  503.     bound" which has been taken as _not_ implying that there will be
  504.     separate bindings for each iteration.) 
  505.  
  506.     Consequently, if you make closures over an iteration variable
  507.     in separate iterations they may nonetheless be closures over
  508.     the same variable and hence will all refer to the same value
  509.     -- whatever value the variable was given last.  For example,
  510.         (let ((fns '()))
  511.           (do ((x '(1 2) (cdr x)))
  512.               ((null x))
  513.             (push #'(lambda () x)
  514.                   fns))
  515.           (mapcar #'funcall (reverse fns)))
  516.     returns (nil nil), not (1 2), not even (2 2). Thus 
  517.          (let ((l nil)) 
  518.            (dolist (a '(1 2 3) l) 
  519.              (push #'(lambda () a)
  520.                    l)))
  521.     returns a list of three closures closed over the same bindings, whereas
  522.          (mapcar #'(lambda (a) #'(lambda () a)) '(1 2 3))
  523.     returns a list of closures over distinct bindings.
  524.  
  525. Defining Variables and Constants:
  526.  
  527.   * (defvar var init) assigns to the variable only if it does not
  528.     already have a value.  So if you edit a DEFVAR in a file and
  529.     reload the file only to find that the value has not changed,
  530.     this is the reason.  (Use DEFPARAMETER if you want the value
  531.     to change upon reloading.) DEFVAR is used to declare a variable
  532.     that is changed by the program; DEFPARAMETER is used to declare
  533.     a variable that is normally constant, but which can be changed
  534.     to change the functioning of a program.
  535.  
  536.   * DEFCONSTANT has several potentially unexpected properties:
  537.  
  538.      - Once a name has been declared constant, it cannot be used a
  539.        the name of a local variable (lexical or special) or function
  540.        parameter.  Really.  See page 87 of CLtL2.
  541.  
  542.      - A DEFCONSTANT cannot be re-evaluated (eg, by reloading the
  543.        file in which it appears) unless the new value is EQL to the
  544.  lowing would be wrong:
  545.  
  546.    (defmacro if (test then-form &optional else-form)
  547.      ;; this evaluates all the subforms at compile time, and at runtime
  548.      ;; evaluates the results again.
  549.      `(cond (,(eval test) ,(eval then-form))
  550.             (t ,(eval else-form))))
  551.  
  552.    (defmacro if (test then-form &optional else-form)
  553.      ;; this double-evaluates at run time
  554.      `(cond ((eval ,test) (eval ,then-form))
  555.             (t (eval ,else-form)))
  556.  
  557. This is correct:
  558.  
  559.    (defmacro if (test then-form &optional else-form)
  560.      `(cond (,test ,then-form)
  561.             (t ,else-form)))
  562.  
  563. The following question (taken from an actual post) is typical of the
  564. kind of question asked by a programmer who is misusing EVAL:
  565.  
  566.    I would like to be able to quote all the atoms except the first in a
  567.    list of atoms.  The purpose is to allow a function to be read in and
  568.    evaluated as if its arguments had been quoted.
  569.  
  570. This is the wrong approach to solving the problem. Instead, he should
  571. APPLY the CAR of the form to the CDR of the form. Then quoting the
  572. rest of the form is unnecessary. But one wonders why he's trying to
  573. solve this problem in the first place, since the toplevel REP loop
  574. already involves a call to EVAL. One gets the feeling that if we knew
  575. more about what he's trying to accomplish, we'd be able to point out a
  576. more appropriate solution that uses neither EVAL nor APPLY.
  577.  
  578. On the other hand, EVAL can sometimes be necessary when the only portable
  579. interface to an operation is a macro. 
  580.  
  581. ----------------------------------------------------------------
  582. Subject: [3-13] Why does my program's behavior change each time I use it?
  583.  
  584. Most likely your program is altering itself, and the most common way this
  585. may happen is by performing destructive operations on embedded constant
  586. data structures.  For instance, consider the following:
  587.  
  588.    (defun one-to-ten-except (n)
  589.      (delete n '(1 2 3 4 5 6 7 8 9 10)))
  590.    (one-to-ten-except 3) => (1 2 4 5 6 7 8 9 10)
  591.    (one-to-ten-except 5) => (1 2 4 6 7 8 9 10) ; 3 is missing
  592.  
  593. The basic problem is that QUOTE returns its argument, *not* a copy of
  594. it. The list is actually a part of the lambda expression that is in
  595. ONE-TO-TEN-EXCEPT's function cell, and any modifications to it (e.g., by
  596. DELETE) are modifications to the actual object in the function definition.
  597. The next time that the function is called, this modified list is used.
  598.  
  599. In some implementations calling ONE-TO-TEN-EXCEPT may even result in
  600. the signalling of an error or the complete aborting of the Lisp process.  Some
  601. Lisp implementations put self-evaluating and quoted constants onto memory
  602. pages that are marked read-only, in order to catch bugs such as this.
  603. Details of this behavior may vary even within an implementation,
  604. depending on whether the code is interpreted or compiled (perhaps due to
  605. inlined DEFCONSTANT objects or constant folding optimizations).
  606.  
  607. All of these behaviors are allowed by the draft ANSI Common Lisp
  608. specification, which specifically states that the consequences of modifying
  609. a constant are undefined (X3J13 vote CONSTANT-MODIFICATION:DISALLOW).
  610.  
  611. To avoid these problems, use LIST to introduce a list, not QUOTE. QUOTE
  612. should be used only when the list is intended to be a constant which
  613. will not be modified.  If QUOTE is used to introduce a list which will
  614. later be modified, use COPY-LIST to provide a fresh copy.
  615.  
  616. For example, the following should all work correctly:
  617.  
  618.    o  (remove 4 (list 1 2 3 4 1 3 4 5))
  619.    o  (remove 4 '(1 2 3 4 1 3 4 5))   ;; Remove is non-destructive.
  620.    o  (delete 4 (list 1 2 3 4 1 3 4 5))
  621.    o  (let ((x (list 1 2 4 1 3 4 5)))
  622.         (delete 4 x))
  623.    o  (defvar *foo* '(1 2 3 4 1 3 4 5))
  624.       (delete 4 (copy-list *foo*))
  625.       (remove 4 *foo*)
  626.       (let ((x (copy-list *foo*)))
  627.          (delete 4 x))
  628.  
  629. The following, however, may not work as expected:
  630.  
  631.    o  (delete 4 '(1 2 3 4 1 3 4 5))
  632.  
  633. Note that similar issues may also apply to hard-coded strings. If you
  634. want to modify elements of a string, create the string with MAKE-STRING.
  635.  
  636. ----------------------------------------------------------------
  637. Subject: [3-14]  When producing formatted output in Lisp, where should you 
  638.         put the newlines (e.g., before or after the line, FRESH-LINE vs TERPRI,
  639.         ~& vs ~% in FORMAT)?
  640.  
  641.  
  642. Where possible, it is desirable to write functions that produce output
  643. as building blocks. In contrast with other languages, which either
  644. conservatively force a newline at various times or require the program
  645. to keep track of whether it needs to force a newline, the Lisp I/O
  646. system keeps track of whether the most recently printed character was
  647. a newline or not. The function FRESH-LINE outputs a newline only if
  648. the stream is not already at the beginning of a line.  TERPRI forces a
  649. newline irrespective of the current state of the stream. These
  650. correspond to the ~& and ~% FORMAT directives, respectively. (If the
  651. Lisp I/O system can't determine whether it's physically at the
  652. beginning of a line, it assumes that a newline is needed, just in case.)
  653.  
  654. Thus, if you want formatted output to be on a line of its own, start
  655. it with ~& and end it with ~%. (Some people will use a ~& also at the
  656. end, but this isn't necessary, since we know a priori that we're not
  657. at the beginning of a line. The only exception is when ~& follows a
  658. ~A, to prevent a double newline when the argument to the ~A is a
  659. formatted string with a newline at the end.) For example, the
  660. following routine prints the elements of a list, N elements per line,
  661. and then prints the total number of elements on a new line:
  662.  
  663.    (defun print-list (list &optional (elements-per-line 10))
  664.      (fresh-line)
  665.      (loop for i upfrom 1
  666.            for element in list do
  667.        (format t "~A ~:[~;~%~]" element (zerop (mod i elements-per-line))))
  668.      (format t "~&~D~%" (length list)))
  669.  
  670. ----------------------------------------------------------------
  671. Subject: [3-15] I'm using DO to do some iteration, but it doesn't terminate. 
  672.  
  673. Your code probably looks something like
  674.    (do ((sublist list (cdr list))
  675.         ..)
  676.        ((endp sublist)
  677.         ..)
  678.      ..)
  679. or maybe
  680.    (do ((index start (+ start 2))
  681.         ..)
  682.        ((= index end)
  683.         ..)
  684.      ..)
  685.  
  686. The problem is caused by the (cdr list) and the (+ start 2) in the
  687. first line. You're using the original list and start index instead of
  688. the working sublist or index. Change them to (cdr sublist) and 
  689. (+ index 2) and your code should start working.
  690.  
  691. ----------------------------------------------------------------
  692. Subject: [3-16] My program works when interpreted but not when compiled!
  693.  
  694. Look for problems with your macro definitions, such as a macro that is
  695. missing a quote. When compiled, this definition essentially becomes a
  696. constant. But when interpreted, the body of the macro is executed each
  697. time the macro is called.
  698.  
  699. For example, in Allegro CL the following code will behave differently
  700. when interpreted and compiled:
  701.   (defvar x 10)
  702.   (defmacro foo () (incf x))
  703.   (defun bar () (+ (foo) (foo)))
  704. Putting a quote before the (incf x) in the definition of foo fixes the
  705. problem. 
  706.  
  707. If you use (SETF (SYMBOL-FUNCTION 'foo) ...) to change the definition
  708. of a built-in Lisp function named FOO, be aware that this may not work
  709. correctly (i.e., as desired) in compiled code in all Lisps. In some
  710. Lisps, the compiler treats certain symbols in the LISP package
  711. specially, ignoring the function definition. If you want to redefine a
  712. standard function try proclaiming/declaring it NOTINLINE prior to
  713. compiling any use that should go through the function cell. (Note that
  714. this is not guarranteed to work, since X3J13 has stated that it is not
  715. permitted to redefine any of the standard functions).
  716.  
  717. ----------------------------------------------------------------
  718. ;;; *EOF*
  719.