home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / answers / lisp-faq / part3 < prev    next >
Encoding:
Text File  |  1993-12-12  |  35.4 KB  |  793 lines

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