home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #18 / NN_1992_18.iso / spool / comp / lang / lisp / 2217 < prev    next >
Encoding:
Internet Message Format  |  1992-08-13  |  22.3 KB

  1. Xref: sparky comp.lang.lisp:2217 news.answers:2478
  2. Path: sparky!uunet!cis.ohio-state.edu!pacific.mps.ohio-state.edu!linac!uwm.edu!ogicse!das-news.harvard.edu!cantaloupe.srv.cs.cmu.edu!crabapple.srv.cs.cmu.edu!mkant
  3. From: mkant+@cs.cmu.edu (Mark Kantrowitz)
  4. Newsgroups: comp.lang.lisp,news.answers
  5. Subject: FAQ: Lisp Frequently Asked Questions 3/5 [Monthly posting]
  6. Summary: Common Pitfalls
  7. Message-ID: <lisp-faq-3.text_713752722@cs.cmu.edu>
  8. Date: 14 Aug 92 00:39:48 GMT
  9. Article-I.D.: cs.lisp-faq-3.text_713752722
  10. Expires: Sun, 27 Sep 1992 00:38:42 GMT
  11. Sender: news@cs.cmu.edu (Usenet News System)
  12. Reply-To: lisp-faq@think.com
  13. Followup-To: poster
  14. Organization: School of Computer Science, Carnegie Mellon
  15. Lines: 494
  16. Approved: news-answers-request@MIT.Edu
  17. Supersedes: <lisp-faq-3.text_711014512@cs.cmu.edu>
  18. Nntp-Posting-Host: a.gp.cs.cmu.edu
  19.  
  20. Archive-name: lisp-faq/part3
  21. Last-Modified: Thu Aug  6 11:54:55 1992 by Mark Kantrowitz
  22. Version: 1.23
  23.  
  24. ;;; ****************************************************************
  25. ;;; Answers to Frequently Asked Questions about Lisp ***************
  26. ;;; ****************************************************************
  27. ;;; Written by Mark Kantrowitz and Barry Margolin
  28. ;;; lisp-faq-3.text -- 21696 bytes
  29.  
  30. This post contains Part 3 of the Lisp FAQ.
  31.  
  32. If you think of questions that are appropriate for this FAQ, or would
  33. like to improve an answer, please send email to us at lisp-faq@think.com.
  34.  
  35. This section contains a list of common pitfalls. Pitfalls are aspects
  36. of Common Lisp which are non-obvious to new programmers and often
  37. seasoned programmers as well.
  38.  
  39. Common Pitfalls (Part 3):
  40.  
  41.   [3-0]  Why does (READ-FROM-STRING "foobar" :START 3) return FOOBAR
  42.          instead of BAR?  
  43.   [3-1]  Why can't it deduce from (READ-FROM-STRING "foobar" :START 3)
  44.          that the intent is to specify the START keyword parameter
  45.          rather than the EOF-ERROR-P and EOF-VALUE optional parameters?   
  46.   [3-2]  Why can't I apply #'AND and #'OR?
  47.   [3-3]  I used a destructive function (e.g. DELETE, SORT), but it
  48.          didn't seem to work.  Why? 
  49.   [3-4]  After I NREVERSE a list, it's only one element long.  After I
  50.          SORT a list, it's missing things.  What happened? 
  51.   [3-5]  Why does (READ-LINE) return "" immediately instead of waiting
  52.          for me to type a line?  
  53.   [3-6]  I typed a form to the read-eval-print loop, but nothing happened. Why?
  54.   [3-7]  DEFMACRO doesn't seem to work.
  55.          When I compile my file, LISP warns me that my macros are undefined
  56.          functions, or complains "Attempt to call <function> which is 
  57.          defined as a macro.
  58.   [3-8]  Name conflict errors are driving me crazy! (EXPORT, packages)
  59.   [3-9]  Closures don't seem to work properly when referring to the
  60.          iteration variable in DOLIST, DOTIMES and DO.
  61.   [3-10] What is the difference between FUNCALL and APPLY?
  62.   [3-11] Miscellaneous things to consider when debugging code.
  63.  
  64. Search for [#] to get to question number # quickly.
  65.  
  66. ----------------------------------------------------------------
  67. [3-0] Why does (READ-FROM-STRING "foobar" :START 3) return FOOBAR instead 
  68.       of BAR?
  69.  
  70. READ-FROM-STRING is one of the rare functions that takes both &OPTIONAL and
  71. &KEY arguments:
  72.  
  73.        READ-FROM-STRING string &OPTIONAL eof-error-p eof-value 
  74.                                &KEY :start :end :preserve-whitespace
  75.  
  76. When a function takes both types of arguments, all the optional
  77. arguments must be specified explicitly before any of the keyword
  78. arguments may be specified.  In the example above, :START becomes the
  79. value of the optional EOF-ERROR-P parameter and 3 is the value of the
  80. optional EOF-VALUE parameter.
  81.      
  82. ----------------------------------------------------------------
  83. [3-1] Why can't it deduce from (READ-FROM-STRING "foobar" :START 3) that
  84.       the intent is to specify the START keyword parameter rather than
  85.       the EOF-ERROR-P and EOF-VALUE optional parameters?
  86.  
  87. In Common Lisp, keyword symbols are first-class data objects.  Therefore,
  88. they are perfectly valid values for optional parameters to functions.
  89. There are only four functions in Common Lisp that have both optional and
  90. keyword parameters (they are PARSE-NAMESTRING, READ-FROM-STRING,
  91. WRITE-LINE, and WRITE-STRING), so it's probably not worth adding a
  92. nonorthogonal kludge to the language just to make these functions slightly
  93. less confusing; unfortunately, it's also not worth an incompatible change
  94. to the language to redefine those functions to use only keyword arguments.
  95.      
  96. ----------------------------------------------------------------
  97. [3-2] Why can't I apply #'AND and #'OR?
  98.  
  99. Here's the simple, but not necessarily satisfying, answer: AND and OR are
  100. macros, not functions; APPLY and FUNCALL can only be used to invoke
  101. functions, not macros and special operators.
  102.  
  103. OK, so what's the *real* reason?  The reason that AND and OR are macros
  104. rather than functions is because they implement control structure in
  105. addition to computing a boolean value.  They evaluate their subforms
  106. sequentially from left/top to right/bottom, and stop evaluating subforms as
  107. soon as the result can be determined (in the case of AND, as soon as a
  108. subform returns NIL; in the case of OR, as soon as one returns non-NIL);
  109. this is referred to as "short circuiting" in computer language parlance.
  110. APPLY and FUNCALL, however, are ordinary functions; therefore, their
  111. arguments are evaluated automatically, before they are called.  Thus, were
  112. APPLY able to be used with #'AND, the short-circuiting would be defeated.
  113.  
  114. Perhaps you don't really care about the short-circuiting, and simply want
  115. the functional, boolean interpretation.  While this may be a reasonable
  116. interpretation of trying to apply AND or OR, it doesn't generalize to other
  117. macros well, so there's no obvious way to have the Lisp system "do the
  118. right thing" when trying to apply macros.  The only function associated
  119. with a macro is its expander function; this function accepts and returns
  120. and form, so it cannot be used to compute the value.
  121.  
  122. The Common Lisp functions EVERY and SOME can be used to get the
  123. functionality you intend when trying to apply #'AND and #'OR.  For
  124. instance, the erroneous form:
  125.  
  126.    (apply #'and *list*)
  127.  
  128. can be translated to the correct form:
  129.  
  130.    (every #'identity *list*)
  131.  
  132. ----------------------------------------------------------------
  133. [3-3] I used a destructive function (e.g. DELETE, SORT), but it didn't seem to
  134.       work.  Why?
  135.  
  136. I assume you mean that it didn't seem to modify the original list.  There
  137. are several possible reasons for this.  First, many destructive functions
  138. are not *required* to modify their input argument, merely *allowed* to; in
  139. some cases, the implementation may determine that it is more efficient to
  140. construct a new result than to modify the original (this may happen in Lisp
  141. systems that use "CDR coding", where RPLACD may have to turn a CDR-NEXT or
  142. CDR-NIL cell into a CDR-NORMAL cell), or the implementor may simply not
  143. have gotten around to implementing the destructive version in a truly
  144. destructive manner.  Another possibility is that the nature of the change
  145. that was made involves removing elements from the front of a list; in this
  146. case, the function can simply return the appropriate tail of the list,
  147. without actually modifying the list. And example of this is:
  148.      
  149.    (setq *a* (list 3 2 1))
  150.    (delete 3 *a*) => (2 1)
  151.    *a* => (3 2 1)
  152.  
  153. Similarly, when one sorts a list, SORT may destructively rearrange the
  154. pointers (cons cells) that make up the list. SORT then returns the cons
  155. cell that now heads the list; the original cons cell could be anywhere in
  156. the list. The value of any variable that contained the original head of the
  157. list hasn't changed, but the contents of that cons cell have changed
  158. because SORT is a destructive function:
  159.  
  160.    (setq *a* (list 2 1 3))
  161.    (sort *a* #'<) => (1 2 3)
  162.    *a* => (2 3)     
  163.  
  164. In both cases, the remedy is the same: store the result of the
  165. function back into the place whence the original value came, e.g.
  166.  
  167.    (setq *a* (delete 3 *a*))
  168.    *a* => (2 1)
  169.  
  170. Why don't the destructive functions do this automatically?  Recall that
  171. they are just ordinary functions, and all Lisp functions are called by
  172. value.  Therefore, these functions do not know where the lists they are
  173. given came from; they are simply passed the cons cell that represents the
  174. head of the list. Their only obligation is to return the new cons cell that
  175. represents the head of the list.
  176.  
  177. One thing to be careful about when doing this is that the original list
  178. might be referenced from multiple places, and all of these places may need
  179. to be updated.  For instance:
  180.  
  181.    (setq *a* (list 3 2 1))
  182.    (setq *b* *a*)
  183.    (setq *a* (delete 3 *a*))
  184.    *a* => (2 1)
  185.    *b* => (3 2 1) ; *B* doesn't "see" the change
  186.    (setq *a* (delete 1 *a*))
  187.    *a* => (2)
  188.    *b* => (3 2) ; *B* sees the change this time, though
  189.  
  190. One may argue that destructive functions could do what you expect by
  191. rearranging the CARs of the list, shifting things up if the first element
  192. is being deleted, as they are likely to do if the argument is a vector
  193. rather than a list.  In many cases they could do this, although it would
  194. clearly be slower.  However, there is one case where this is not possible:
  195. when the argument or value is NIL, and the value or argument, respectively,
  196. is not.  It's not possible to transform the object referenced from the
  197. original cell from one data type to another, so the result must be stored
  198. back.  Here are some examples:
  199.  
  200.    (setq *a* (list 3 2 1))
  201.    (delete-if #'numberp *a) => NIL
  202.    *a* => (3 2 1)
  203.    (setq *a* nil *b* '(1 2 3))
  204.    (nconc *a* *b*) => (1 2 3)
  205.    *a* => NIL
  206.  
  207. The names of most destructure functions (except for sort, delete,
  208. rplaca, rplacd, and setf of accessor functions) have the prefix N.
  209.  
  210. In summary, the two common problems to watch out for when using
  211. destructive functions are:
  212.  
  213.    1. Forgetting to store the result back. Even though the list
  214.       is modified in place, it is still necessary to store the
  215.       result of the function back into the original location, e.g.,
  216.            (setq foo (delete 'x foo))
  217.  
  218.       If the original list was stored in multiple places, you may
  219.       need to store it back in all of them, e.g.
  220.            (setq bar foo)
  221.            ...
  222.            (setq foo (delete 'x foo))
  223.            (setq bar foo)
  224.  
  225.    2. Sharing structure that gets modified. If it is important
  226.       to preserve the shared structure, then you should either
  227.       use a nondestructive operation or copy the structure first
  228.       using COPY-LIST or COPY-TREE.
  229.            (setq bar (cdr foo))
  230.            ...
  231.            (setq foo (sort foo #'<))
  232.            ;;; now it's not safe to use BAR
  233.  
  234. Note that even nondestructive functions, such as REMOVE, and UNION,
  235. can return a result which shares structure with an argument. 
  236. Nondestructive functions don't necessarily copy their arguments; they
  237. just don't modify them.
  238.      
  239. ----------------------------------------------------------------
  240. [3-4] After I NREVERSE a list, it's only one element long.  After I SORT
  241.       a list, it's missing things.  What happened?
  242.  
  243. These are particular cases of the previous question.  Many NREVERSE and
  244. SORT implementations operate by rechaining all the CDR links in the list's
  245. backbone, rather than by replacing the CARs.  In the case of NREVERSE, this
  246. means that the cons cell that was originally first in the list becomes the
  247. last one.  As in the last question, the solution is to store the result
  248. back into the original location.
  249.      
  250. ----------------------------------------------------------------
  251. [3-5] Why does (READ-LINE) return "" immediately instead of waiting for
  252.       me to type a line?
  253.  
  254. Many Lisp implementations on line-buffered systems do not discard the
  255. newline that the user must type after the last right parenthesis in order
  256. for the line to be transmitted from the OS to Lisp.  Lisp's READ function
  257. returns immediately after seeing the matching ")" in the stream.  When
  258. READLINE is called, it sees the next character in the stream, which is a
  259. newline, so it returns an empty line.  If you were to type "(read-line)This
  260. is a test" the result would be "This is a test".
  261.  
  262. The simplest solution is to use (PROGN (CLEAR-INPUT) (READ-LINE)).  This
  263. discards the buffered newline before reading the input.  However, it would
  264. also discard any other buffered input, as in the "This is a test" example
  265. above; some implementation also flush the OS's input buffers, so typeahead
  266. might be thrown away.
  267.  
  268. ----------------------------------------------------------------
  269. [3-6] I typed a form to the read-eval-print loop, but nothing happened. Why?
  270.  
  271. There's not much to go on here, but a common reason is that you haven't
  272. actually typed a complete form.  You may have typed a doublequote, vertical
  273. bar, "#|" comment beginning, or left parenthesis that you never matched
  274. with another doublequote, vertical bar, "|#", or right parenthesis,
  275. respectively.  Try typing a few right parentheses followed by Return.
  276.  
  277. ----------------------------------------------------------------
  278. [3-7]  DEFMACRO doesn't seem to work. 
  279.        When I compile my file, LISP warns me that my macros are undefined
  280.        functions, or complains "Attempt to call <function> which is 
  281.        defined as a macro.
  282.  
  283. When you evaluate a DEFMACRO form or proclaim a function INLINE, it
  284. doesn't go back and update code that was compiled under the old
  285. definition. When redefining a macro, be sure to recompile any
  286. functions that use the macro. Also be sure that the macros used in a
  287. file are defined before any forms in the same file that use them.
  288.  
  289. Certain forms, including LOAD, SET-MACRO-CHARACTER, and
  290. REQUIRE, are not normally evaluated at compile time. Common Lisp
  291. requires that macros defined in a file be used when compiling later
  292. forms in the file. If a Lisp doesn't follow the standard, it may be
  293. necessary to wrap an EVAL-WHEN form around the macro definition.
  294.  
  295. Most often the "macro was previously called as a function" problem
  296. occurs when files were compiled/loaded in the wrong order. For
  297. example, developers may add the definition to one file, but use it in
  298. a file which is compiled/loaded before the definition. To work around
  299. this problem, one can either fix the modularization of the system, or
  300. manually recompile the files containing the forward references to macros.
  301.  
  302. Also, if your macro calls functions at macroexpand time, those functions
  303. may need to be in an EVAL-WHEN. For example,
  304.  
  305.     (defun some-function (x)
  306.       x)
  307.  
  308.     (defmacro some-macro (y)
  309.       (let ((z (some-function y)))
  310.     `(print ',z)))
  311.  
  312. If the macros are defined in a file you require, make sure your
  313. require or load statement is in an appropriate EVAL-WHEN. Many people
  314. avoid all this nonsense by making sure to load all their files before
  315. compiling them, or use a system facility (or just a script file) that
  316. loads each file before compiling the next file in the system.
  317.  
  318. ----------------------------------------------------------------
  319. [3-8]  Name conflict errors are driving me crazy! (EXPORT, packages)
  320.  
  321. If a package tries to export a symbol that's already defined, it will
  322. report an error. You probably tried to use a function only to discover
  323. that you'd forgotten to load its file. The failed attempt at using the
  324. function caused its symbol to be interned. So now, when you try to
  325. load the file, you get a conflict. Unfortunately, understanding and
  326. correcting the code which caused the export problem doesn't make those
  327. nasty error messages go away. That symbol is still interned where it
  328. shouldn't be. Use unintern to remove the symbol from a package before
  329. reloading the file. Also, when giving arguments to REQUIRE or package
  330. functions, use strings or keywords, not symbols: (find-package "FOO"),
  331. (find-package :foo). 
  332.  
  333. A sometimes useful technique is to rename (or delete) a package
  334. that is "too messed up".  Then you can reload the relevant files
  335. into a "clean" package.
  336.  
  337. ----------------------------------------------------------------
  338. [3-9]  Closures don't seem to work properly when referring to the
  339.        iteration variable in DOLIST, DOTIMES and DO.
  340.  
  341. DOTIMES, DOLIST, and DO all use assignment instead of binding to
  342. update the value of the iteration variables. So something like
  343.  
  344.    (dotimes (n 10)
  345.      (push #'(lambda () (incf n))
  346.            *counters*))
  347.  
  348. will produce 10 closures over the same value of the variable N.
  349. ----------------------------------------------------------------
  350. [3-10] What is the difference between FUNCALL and APPLY?
  351.  
  352. FUNCALL is useful when the programmer knows the length of the argument
  353. list, but the function to call is either computed or provided as a
  354. parameter.  For instance, a simple implementation of MEMBER-IF (with
  355. none of the fancy options) could be written as:
  356.  
  357. (defun member-if (predicate list)
  358.   (do ((tail list (cdr tail)))
  359.       ((null tail))
  360.    (when (funcall predicate (car tail))
  361.      (return-from member-if tail))))
  362.  
  363. The programmer is invoking a caller-supplied function with a known
  364. argument list.
  365.  
  366. APPLY is needed when the argument list itself is supplied or computed.
  367. Its last argument must be a list, and the elements of this list become
  368. individual arguments to the function.  This frequently occurs when a
  369. function takes keyword options that will be passed on to some other
  370. function, perhaps with application-specific defaults inserted.  For
  371. instance:
  372.  
  373. (defun open-for-output (pathname &rest open-options)
  374.   (apply #'open pathname :direction :output open-options))
  375.  
  376. FUNCALL could actually have been defined using APPLY:
  377.  
  378. (defun funcall (function &rest arguments)
  379.   (apply function arguments))
  380.  
  381. ----------------------------------------------------------------
  382. [3-11] Miscellaneous things to consider when debugging code.
  383.  
  384. This question lists a variety of problems to watch out for when
  385. debugging code. This is sort of a catch-all question for problems too
  386. small to merit a question of their own. See also question [1-2] for
  387. some other common problems.
  388.  
  389. Functions:
  390.  
  391.   * (flet ((f ...)) (eq #'f #'f)) can return false.
  392.  
  393.   * The function LIST-LENGTH is not a faster, list-specific version
  394.     of the sequence function LENGTH.  It is list-specific, but it's
  395.     slower than LENGTH because it can handle circular lists.
  396.  
  397.   * Some destructive functions that you think would modify CDRs might
  398.     modify CARs instead.  (E.g., NREVERSE.)
  399.  
  400.   * READ-FROM-STRING has some optional arguments before the
  401.     keyword parameters.  If you want to supply some keyword
  402.     arguments, you have to give all of the optional ones too.
  403.  
  404.   * If you use the function READ-FROM-STRING, you should probably bind
  405.     *READ-EVAL* to NIL. Otherwise an unscrupulous user could cause a
  406.     lot of damage by entering 
  407.     #.(shell "cd; rm -R *")
  408.     at a prompt.
  409.  
  410. Methods:
  411.  
  412.   * PRINT-OBJECT methods can make good code look buggy. If there is a
  413.     problem with the PRINT-OBJECT methods for one of your classes, it
  414.     could make it seem as though there were a problem with the object.
  415.     It can be very annoying to go chasing through your code looking for
  416.     the cause of the wrong value, when the culprit is just a bad
  417.     PRINT-OBJECT method.
  418.  
  419. Initialization:
  420.  
  421.   * Don't count on array elements being initialized to NIL, if you don't
  422.     specify an :initial-element argument to MAKE-ARRAY. For example,
  423.          (make-array 10) => #(0 0 0 0 0 0 0 0 0 0)
  424.  
  425. Iteration vs closures:
  426.  
  427.   * DO and DO* update the iteration variables by assignment; DOLIST and
  428.     DOTIMES are allowed to use assignment (rather than a new binding).
  429.     (All CLtL says of DOLIST and DOTIMES is that the variable "is
  430.     bound" which has been taken as _not_ implying that there will be
  431.     separate bindings for each iteration.)
  432.  
  433.     Consequently, if you make closures over an iteration variable
  434.     in separate iterations they may nonetheless be closures over
  435.     the same variable and hence will all refer to the same value
  436.     -- whatever value the variable was given last.  Eg,
  437.  
  438.      (let ((fns '()))
  439.        (do ((x '(1 2) (cdr x)))
  440.            ((null x))
  441.          (push #'(lambda () x)
  442.                fns))
  443.        (mapcar #'funcall (reverse fns)))
  444.  
  445.     returns (nil nil), not (1 2), not even (2 2).
  446.  
  447. Defining Variables and Constants:
  448.  
  449.   * (DEFVAR var init) assigns to the variable only if it does not
  450.     already have a value.  So if you edit a DEFVAR in a file and
  451.     reload the file only to find that the value has not changed,
  452.     this is the reason.  (Use DEFPARAMETER if you want the value
  453.     to change upon reloading.)
  454.  
  455.   * DEFCONSTANT has several potentially unexpected properties:
  456.  
  457.      - Once a name has been declared constant, it cannot be used a
  458.        the name of a local variable (lexical or special) or function
  459.        parameter.  Really.  See page 87 of CLtL II.
  460.  
  461.      - A DEFCONSTANT cannot be re-evaluated (eg, by reloading the
  462.        file in which it appears) unless the new value is EQL to the
  463.        old one.  Strictly speaking, even that may not be allowed.
  464.        (DEFCONSTANT is "like DEFPARAMETER" and hence does an
  465.        assignment, which is not allowed if the name has already
  466.        been declared constant by DEFCONSTANT.)
  467.  
  468.        Note that this makes it difficult to use anything other
  469.        than numbers, symbols, and characters as constants.       
  470.  
  471.      - When compiling (DEFCONSTANT name form) in a file, the form
  472.        may be evaluated at compile-time, load-time, or both.  
  473.  
  474.        (You might think it would be evaluated at compile-time and
  475.        the _value_ used to obtain the object at load-time, but it
  476.        doesn't have to work that way.)
  477.  
  478. Declarations:
  479.  
  480.   * You often have to declare the result type to get the most
  481.     efficient arithmetic.  Eg, 
  482.  
  483.        (the fixnum (+ (the fixnum e1) (the fixnum e2)))
  484.  
  485.      rather than
  486.  
  487.        (+ (the fixnum e1) (the fixnum e2))
  488.  
  489.   * Declaring the iteration variable of a DOTIMES to have type FIXNUM
  490.     does not guarantee that fixnum arithmetic will be used.  That is,
  491.     implementations that use fixnum-specific arithmetic in the presence
  492.     of appropriate declaration may not think _this_ declaration is
  493.     sufficient.  It may help to declare that the limit is also a
  494.     fixnum, or you may have to write out the loop as a DO and add
  495.     appropriate declarations for each operation involved.
  496.  
  497. Miscellaneous:
  498.  
  499.   * Be careful of circular lists and shared list structure. 
  500.  
  501.   * Watch out for macro redefinitions.
  502.  
  503.   * If you use (SETF SYMBOL-FUNCTION) to change the definition of
  504.     built-in Lisp functions, be aware that this may not work correctly
  505.     (i.e., as desired) in compiled code in all Lisps. In some Lisps, 
  506.     the compiler treats certain symbols in the LISP package specially,
  507.     ignoring the function definition.
  508.  
  509.   * A NOTINLINE may be needed if you want SETF of SYMBOL-FUNCTION to
  510.     affect calls within a file.  (See CLtL2, page 686.)
  511.  
  512. ----------------------------------------------------------------
  513. ;;; *EOF*
  514.