home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / xl21hos2.zip / LISP-TUT.DOC < prev    next >
Lisp/Scheme  |  1995-12-27  |  31KB  |  1,110 lines

  1. This looked like a pretty good tutorial -- I found it in the CLISP package.
  2. So I modified it for XLISP. Very few changes were needed.
  3.  
  4. Tom Almy
  5. 12/95
  6.  
  7.  
  8.                           Common LISP Hints
  9.                           Geoffrey J. Gordon
  10.                          <ggordon@cs.cmu.edu>
  11.                        Friday, February 5, 1993
  12.  
  13.                             Modified by
  14.                             Bruno Haible
  15.                 <haible@ma2s2.mathematik.uni-karlsruhe.de>
  16.  
  17. Note: This tutorial introduction to Common Lisp was written for the
  18. CMU environment, so some of the details of running lisp toward the end
  19. may differ from site to site.
  20.  
  21.  
  22. Further Information
  23.  
  24. The best LISP textbook I know of is
  25.  
  26.   Guy L. Steele Jr. _Common LISP: the Language_. Digital Press. 1984.
  27.  
  28. The first edition is easier to read; the second describes a more recent
  29. standard. (The differences between the two standards shouldn't affect
  30. casual programmers.)
  31.  
  32. A book by Dave Touretsky has also been recommended to me, although I
  33. haven't read it, so I can't say anything about it.
  34.  
  35.  
  36.  
  37. Symbols
  38.  
  39. A symbol is just a string of characters. There are restrictions on what
  40. you can include in a symbol and what the first character can be, but as
  41. long as you stick to letters, digits, and hyphens, you'll be safe.
  42. (Except that if you use only digits and possibly an initial hyphen,
  43. LISP will think you typed an integer rather than a symbol.) Some
  44. examples of symbols:
  45.  
  46.         a
  47.         b
  48.         c1
  49.         foo
  50.         bar
  51.         baaz-quux-garply
  52.  
  53. Some things you can do with symbols follow. (Things after a ">" prompt
  54. are what you type to the LISP interpreter, while other things are what
  55. the LISP interpreter prints back to you. The ";" is LISP's comment
  56. character: everything from a ";" to the end of line is ignored.)
  57.  
  58. > (setq a 5)            ;store a number as the value of a symbol
  59. 5
  60. > a                     ;take the value of a symbol
  61. 5
  62. > (let ((a 6)) a)       ;bind the value of a symbol temporarily to 6
  63. 6
  64. > a                     ;the value returns to 5 once the let is finished
  65. 5
  66. > (+ a 6)               ;use the value of a symbol as an argument to a function
  67. 11
  68. > b                     ;try to take the value of a symbol which has no value
  69. error: unbound variable - b               
  70. if continued: try evaluating symbol again 
  71.  
  72. There are two special symbols, t and nil. The value of t is defined
  73. always to be t, and the value of nil is defined always to be nil. LISP
  74. uses t and nil to represent true and false. An example of this use is
  75. in the if statement, described more fully later:
  76.  
  77. > (if t 5 6)
  78. 5
  79. > (if nil 5 6)
  80. 6
  81. > (if 4 5 6)
  82. 5
  83.  
  84. The last example is odd but correct: nil means false, and anything else
  85. means true. (Unless we have a reason to do otherwise, we use t to mean
  86. true, just for the sake of clarity.)
  87.  
  88. Symbols like t and nil are called self-evaluating symbols, because
  89. they evaluate to themselves. There is a whole class of self-evaluating
  90. symbols called keywords; any symbol whose name starts with a colon is a
  91. keyword. (See below for some uses for keywords.) Some examples:
  92.  
  93. > :this-is-a-keyword
  94. :THIS-IS-A-KEYWORD
  95. > :so-is-this
  96. :SO-IS-THIS
  97. > :me-too
  98. :ME-TOO
  99.  
  100.  
  101.  
  102. Numbers
  103.  
  104. An integer is a string of digits optionally preceded by + or -. A real
  105. number looks like an integer, except that it has a decimal point and
  106. optionally can be written in scientific notation. A rational looks like
  107. two integers with a / between them. LISP supports complex numbers,
  108. which are written #c(r i) (where r is the real part and i is the
  109. imaginary part). A number is any of the above. Here are some numbers:
  110.  
  111.         5
  112.         17
  113.         -34
  114.         +6
  115.         3.1415
  116.         1.722e-15
  117.         #c(1.722e-15 0.75)
  118.  
  119. The standard arithmetic functions are all available: +, -, *, /, floor,
  120. ceiling, mod, sin, cos, tan, sqrt, exp, expt, and so forth. All of them
  121. accept any kind of number as an argument. +, -, *, and / return a
  122. number according to type contagion: an integer plus a rational is a
  123. rational, a rational plus a real is a real, and a real plus a complex
  124. is a complex. Here are some examples:
  125.  
  126. > (+ 3 3/4)             ;type contagion
  127. 15/4 
  128. > (exp 1)               ;e
  129. 2.71828 
  130. > (exp 3)               ;e*e*e
  131. 20.0855 
  132. > (expt 3 4.2)          ;exponent with a base other than e
  133. 100.904
  134. > (+ 5 6 7 (* 8 9 10))  ;the fns +-*/ all accept multiple arguments
  135.  
  136. There is no limit to the absolute value of an integer except the memory
  137. size of your computer. Be warned that computations with bignums (as
  138. large integers are called) can be slow. (So can computations with
  139. rationals, especially compared to the corresponding computations with
  140. small integers or floats.)
  141.  
  142.  
  143.  
  144. Conses
  145.  
  146. A cons is just a two-field record. The fields are called "car" and
  147. "cdr", for historical reasons. (On the first machine where LISP was
  148. implemented, there were two instructions CAR and CDR which stood for
  149. "contents of address register" and "contents of decrement register".
  150. Conses were implemented using these two registers.)
  151.  
  152. Conses are easy to use:
  153.  
  154. > (cons 4 5)            ;Allocate a cons. Set the car to 4 and the cdr to 5.
  155. (4 . 5)
  156. > (cons (cons 4 5) 6)
  157. ((4 . 5) . 6)
  158. > (car (cons 4 5))
  159. 4
  160. > (cdr (cons 4 5))
  161. 5
  162.  
  163.  
  164.  
  165. Lists
  166.  
  167. You can build many structures out of conses. Perhaps the simplest is a
  168. linked list: the car of each cons points to one of the elements of the
  169. list, and the cdr points either to another cons or to nil. You can
  170. create such a linked list with the list fuction:
  171.  
  172. > (list 4 5 6)
  173. (4 5 6)
  174.  
  175. Notice that LISP prints linked lists a special way: it omits some of
  176. the periods and parentheses. The rule is: if the cdr of a cons is nil,
  177. LISP doesn't bother to print the period or the nil; and if the cdr of
  178. cons A is cons B, then LISP doesn't bother to print the period for cons
  179. A or the parentheses for cons B. So:
  180.  
  181. > (cons 4 nil)
  182. (4)
  183. > (cons 4 (cons 5 6))
  184. (4 5 . 6)
  185. > (cons 4 (cons 5 (cons 6 nil)))
  186. (4 5 6)
  187.  
  188. The last example is exactly equivalent to the call (list 4 5 6). Note
  189. that nil now means the list with no elements: the cdr of (a b), a list
  190. with 2 elements, is (b), a list with 1 element; and the cdr of (b), a
  191. list with 1 element, is nil, which therefore must be a list with no
  192. elements.
  193.  
  194. The car and cdr of nil are defined to be nil.
  195.  
  196. If you store your list in a variable, you can make it act like a stack:
  197.  
  198. > (setq a nil)
  199. NIL
  200. > (push 4 a)
  201. (4)
  202. > (push 5 a)
  203. (5 4)
  204. > (pop a)
  205. 5
  206. > a
  207. (4)
  208. > (pop a)
  209. 4
  210. > (pop a)
  211. NIL
  212. > a
  213. NIL
  214.  
  215.  
  216.  
  217. Functions
  218.  
  219. You saw one example of a function above. Here are some more:
  220.  
  221. > (+ 3 4 5 6)                   ;this function takes any number of arguments
  222. 18
  223. > (+ (+ 3 4) (+ (+ 4 5) 6))     ;isn't prefix notation fun?
  224. 22
  225. > (defun foo (x y) (+ x y 5))   ;defining a function
  226. FOO
  227. > (foo 5 0)                     ;calling a function
  228. 10
  229. > (defun fact (x)               ;a recursive function
  230.     (if (> x 0) 
  231.       (* x (fact (- x 1)))
  232.       1
  233.   ) )
  234. FACT
  235. > (fact 5)
  236. 120
  237. > (defun a (x) (if (= x 0) t (b (- x))))        ;mutually recursive functions
  238. A
  239. > (defun b (x) (if (> x 0) (a (- x 1)) (a (+ x 1))))
  240. B
  241. > (a 5)
  242. T
  243. > (defun bar (x)                ;a function with multiple statements in
  244.     (setq x (* x 3))            ;its body -- it will return the value
  245.     (setq x (/ x 2))            ;returned by its final statement
  246.     (+ x 4)
  247.   )
  248. BAR
  249. > (bar 6)
  250. 13
  251.  
  252. When we defined foo, we gave it two arguments, x and y. Now when we
  253. call foo, we are required to provide exactly two arguments: the first
  254. will become the value of x for the duration of the call to foo, and the
  255. second will become the value of y for the duration of the call. In
  256. LISP, most variables are lexically scoped; that is, if foo calls bar
  257. and bar tries to reference x, bar will not get foo's value for x.
  258.  
  259. The process of assigning a symbol a value for the duration of some
  260. lexical scope is called binding.
  261.  
  262. You can specify optional arguments for your functions. Any argument
  263. after the symbol &optional is optional:
  264.  
  265. > (defun bar (x &optional y) (if y x 0))
  266. BAR
  267. > (defun baaz (&optional (x 3) (z 10)) (+ x z))
  268. BAAZ
  269. > (bar 5)
  270. 0
  271. > (bar 5 t)
  272. 5
  273. > (baaz 5)
  274. 15
  275. > (baaz 5 6)
  276. 11
  277. > (baaz)
  278. 13
  279.  
  280. It is legal to call the function bar with either one or two arguments.
  281. If it is called with one argument, x will be bound to the value of that
  282. argument and y will be bound to nil; if it is called with two
  283. arguments, x and y will be bound to the values of the first and second
  284. argument, respectively.
  285.  
  286. The function baaz has two optional arguments. It specifies a default
  287. value for each of them: if the caller specifies only one argument, z
  288. will be bound to 10 instead of to nil, and if the caller specifies no
  289. arguments, x will be bound to 3 and z to 10.
  290.  
  291. You can make your function accept any number of arguments by ending its
  292. argument list with an &rest parameter. LISP will collect all arguments
  293. not otherwise accounted for into a list and bind the &rest parameter to
  294. that list. So:
  295.  
  296. > (defun foo (x &rest y) y)
  297. FOO
  298. > (foo 3)
  299. NIL
  300. > (foo 4 5 6)
  301. (5 6)
  302.  
  303. Finally, you can give your function another kind of optional argument
  304. called a keyword argument. The caller can give these arguments in any
  305. order, because they're labelled with keywords.
  306.  
  307. > (defun foo (&key x y) (cons x y))
  308. FOO
  309. > (foo :x 5 :y 3)
  310. (5 . 3)
  311. > (foo :y 3 :x 5)
  312. (5 . 3)
  313. > (foo :y 3)
  314. (NIL . 3)
  315. > (foo)
  316. (NIL)
  317.  
  318. An &key parameter can have a default value too:
  319.  
  320. > (defun foo (&key (x 5)) x)
  321. FOO
  322. > (foo :x 7)
  323. 7
  324. > (foo)
  325. 5
  326.  
  327.  
  328.  
  329. Printing
  330.  
  331. Some functions can cause output. The simplest one is print, which
  332. prints its argument and then returns it.
  333.  
  334. > (print 3)
  335. 3
  336. 3
  337.  
  338. The first 3 above was printed, the second was returned.
  339.  
  340. If you want more complicated output, you will need to use format.
  341. Here's an example:
  342.  
  343. > (format t "An atom: ~S~%and a list: ~S~%and an integer: ~D~%"
  344.           nil (list 5) 6)
  345. An atom: NIL
  346. and a list: (5)
  347. and an integer: 6
  348.  
  349. The first argument to format is either t, nil, or a stream. T specifies
  350. output to the terminal. Nil means not to print anything but to return a
  351. string containing the output instead. Streams are general places for
  352. output to go: they can specify a file, or the terminal, or another
  353. program. This handout will not describe streams in any further detail.
  354.  
  355. The second argument is a formatting template, which is a string
  356. optionally containing formatting directives.
  357.  
  358. All remaining arguments may be referred to by the formatting
  359. directives. LISP will replace the directives with some appropriate
  360. characters based on the arguments to which they refer and then print
  361. the resulting string.
  362.  
  363. Format always returns nil unless its first argument is nil, in which
  364. case it prints nothing and returns a string.
  365.  
  366. There are three different directives in the above example: ~S, ~D, and
  367. ~%. The first one accepts any LISP object and is replaced by a printed
  368. representation of that object (the same representation which is
  369. produced by print). The second one accepts only integers. The third one
  370. doesn't refer to an argument; it is always replaced by a carriage
  371. return.
  372.  
  373. Another useful directive is ~~, which is replaced by a single ~.
  374.  
  375. Refer to a LISP manual for (many, many) additional formatting
  376. directives.
  377.  
  378.  
  379.  
  380. Forms and the Top-Level Loop
  381.  
  382. The things which you type to the LISP interpreter are called forms; the
  383. LISP interpreter repeatedly reads a form, evaluates it, and prints the
  384. result. This procedure is called the read-eval-print loop.
  385.  
  386. Some forms will cause errors. After an error, LISP will put you into
  387. the debugger so you can try to figure out what caused the error. LISP
  388. debuggers are all different; but most will respond to the command
  389. "help" or ":help" by giving some form of help.
  390.  
  391. In general, a form is either an atom (for example, a symbol, an
  392. integer, or a string) or a list. If the form is an atom, LISP evaluates
  393. it immediately. Symbols evaluate to their value; integers and strings
  394. evaluate to themselves. If the form is a list, LISP treats its first
  395. element as the name of a function; it evaluates the remaining elements
  396. recursively, and then calls the function with the values of the
  397. remaining elements as arguments.
  398.  
  399. For example, if LISP sees the form (+ 3 4), it treats + as the name of
  400. a function. It then evaluates 3 to get 3 and 4 to get 4; finally it
  401. calls + with 3 and 4 as the arguments. The + function returns 7, which
  402. LISP prints.
  403.  
  404. The top-level loop provides some other conveniences; one particularly
  405. convenient convenience is the ability to talk about the results of
  406. previously typed forms. LISP always saves its most recent three
  407. results; it stores them as the values of the symbols *, **, and ***.
  408. For example:
  409.  
  410. > 3
  411. 3
  412. > 4
  413. 4
  414. > 5
  415. 5
  416. > ***
  417. 3
  418. > ***
  419. 4
  420. > ***
  421. 5
  422. > **
  423. 4
  424. > *
  425. 4
  426.  
  427.  
  428.  
  429. Special forms
  430.  
  431. There are a number of special forms which look like function calls but
  432. aren't. These include control constructs such as if statements and do
  433. loops; assignments like setq, setf, push, and pop; definitions such as
  434. defun and defstruct; and binding constructs such as let. (Not all of
  435. these special forms have been mentioned yet. See below.)
  436.  
  437. One useful special form is the quote form: quote prevents its argument
  438. from being evaluated. For example:
  439.  
  440. > (setq a 3)
  441. 3
  442. > a
  443. 3
  444. > (quote a)
  445. A
  446. > 'a                    ;'a is an abbreviation for (quote a)
  447. A
  448.  
  449. Another similar special form is the function form: function causes its
  450. argument to be interpreted as a function rather than being evaluated.
  451. For example:
  452.  
  453. > (setq + 3)
  454. 3
  455. > +
  456. 3
  457. > '+
  458. +
  459. > (function +)
  460. #<Subr-+: #88b44d5e> 
  461. > #'+                   ;#'+ is an abbreviation for (function +)
  462. #<Subr-+: #88b44d5e> 
  463.  
  464. The function special form is useful when you want to pass a function as
  465. an argument to another function. See below for some examples of
  466. functions which take functions as arguments.
  467.  
  468.  
  469.  
  470. Binding
  471.  
  472. Binding is lexically scoped assignment. It happens to the variables in
  473. a function's parameter list whenever the function is called: the formal
  474. parameters are bound to the actual parameters for the duration of the
  475. function call. You can bind variables anywhere in a program with the
  476. let special form, which looks like this:
  477.  
  478.         (let ((var1 val1)
  479.               (var2 val2)
  480.               ...
  481.              )
  482.           body
  483.         )
  484.  
  485. Let binds var1 to val1, var2 to val2, and so forth; then it executes
  486. the statements in its body. The body of a let follows exactly the same
  487. rules that a function body does. Some examples:
  488.  
  489. > (let ((a 3)) (+ a 1))
  490. 4
  491. > (let ((a 2) 
  492.         (b 3)
  493.         (c 0))
  494.     (setq c (+ a b))
  495.     c
  496.   )
  497. 5
  498. > (setq c 4)
  499. 4
  500. > (let ((c 5)) c)
  501. 5
  502. > c
  503. 4
  504.  
  505. Instead of (let ((a nil) (b nil)) ...), you can write (let (a b) ...).
  506.  
  507. The val1, val2, etc. inside a let cannot reference the variables var1,
  508. var2, etc. that the let is binding. For example,
  509.  
  510. > (let ((x 1)
  511.         (y (+ x 1)))
  512.     y
  513.   )
  514. error: unbound variable - x       
  515.  
  516. If the symbol x already has a global value, stranger happenings will
  517. result:
  518.  
  519. > (setq x 7)
  520. 7
  521. > (let ((x 1)
  522.         (y (+ x 1)))
  523.     y
  524.   )
  525. 8
  526.  
  527. The let* special form is just like let except that it allows values to
  528. reference variables defined earlier in the let*. For example,
  529.  
  530. > (setq x 7)
  531. 7
  532. > (let* ((x 1)
  533.          (y (+ x 1)))
  534.     y
  535.   )
  536. 2
  537.  
  538. The form
  539.  
  540.         (let* ((x a)
  541.                (y b))
  542.           ...
  543.         ) 
  544.  
  545. is equivalent to
  546.  
  547.         (let ((x a))
  548.           (let ((y b))
  549.             ...
  550.         ) )
  551.  
  552.  
  553.  
  554. Dynamic Scoping
  555.  
  556. The let and let* forms provide lexical scoping, which is what you
  557. expect if you're used to programming in C or Pascal. Dynamic scoping is
  558. what you get in BASIC: if you assign a value to a dynamically scoped
  559. variable, every mention of that variable returns that value until you
  560. assign another value to the same variable.
  561.  
  562. In LISP, dynamically scoped variables are called special variables. You
  563. can declare a special variable with the defvar special form. Here are
  564. some examples of lexically and dynamically scoped variables.
  565.  
  566. In this example, the function check-regular references a regular (ie,
  567. lexically scoped) variable. Since check-regular is lexically outside of
  568. the let which binds regular, check-regular returns the variable's
  569. global value.
  570.  
  571. > (setq regular 5)
  572. > (defun check-regular () regular)
  573. CHECK-REGULAR 
  574. > (check-regular)
  575. > (let ((regular 6)) (check-regular))
  576.  
  577. In this example, the function check-special references a special (ie,
  578. dynamically scoped) variable. Since the call to check-special is
  579. temporally inside of the let which binds special, check-special returns
  580. the variable's local value.
  581.  
  582. > (defvar *special* 5)
  583. *SPECIAL*
  584. > (defun check-special () *special*)
  585. CHECK-SPECIAL
  586. > (check-special)
  587. 5
  588. > (let ((*special* 6)) (check-special))
  589. 6
  590.  
  591. By convention, the name of a special variable begins and ends with a *.
  592. Special variables are chiefly used as global variables, since
  593. programmers usually expect lexical scoping for local variables and
  594. dynamic scoping for global variables.
  595.  
  596. For more information on the difference between lexical and dynamic
  597. scoping, see _Common LISP: the Language_.
  598.  
  599.  
  600.  
  601. Arrays
  602.  
  603. The function make-array makes a 1D array. The aref function accesses its
  604. elements. All elements of an array are initially set to nil. For
  605. example:
  606.  
  607. > (make-array 4)        ;1D arrays don't need the extra parens
  608. #(NIL NIL NIL NIL)
  609.  
  610. Array indices always start at 0.
  611.  
  612. See below for how to set the elements of an array.
  613.  
  614.  
  615.  
  616. Strings
  617.  
  618. A string is a sequence of characters between double quotes. LISP
  619. represents a string as a variable-length array of characters. You can
  620. write a string which contains a double quote by preceding the quote
  621. with a backslash; a double backslash stands for a single backslash. For
  622. example:
  623.  
  624.         "abcd" has 4 characters
  625.         "\"" has 1 character
  626.         "\\" has 1 character
  627.  
  628. Here are some functions for dealing with strings:
  629.  
  630. > (concatenate 'string "abcd" "efg")
  631. "abcdefg"
  632. > (char "abc" 1)
  633. #\b                     ;LISP writes characters preceded by #\
  634. > (aref "abc" 1)
  635. #\b                     ;remember, strings are really arrays
  636.  
  637. The concatenate function can actually work with any type of sequence:
  638.  
  639. > (concatenate 'string '(#\a #\b) '(#\c))
  640. "abc"
  641. > (concatenate 'list "abc" "de")
  642. (#\a #\b #\c #\d #\e)
  643. > (concatenate 'array '#(3 3 3) '#(3 3 3))
  644. #(3 3 3 3 3 3)
  645.  
  646.  
  647.  
  648. Structures
  649.  
  650. LISP structures are analogous to C structs or Pascal records. Here is
  651. an example:
  652.  
  653. > (defstruct foo
  654.     bar
  655.     baaz
  656.     quux
  657.   )
  658. FOO
  659.  
  660. This example defines a data type called foo which is a structure
  661. containing 3 fields. It also defines 4 functions which operate on this
  662. data type: make-foo, foo-bar, foo-baaz, and foo-quux. The first one
  663. makes a new object of type foo; the others access the fields of an
  664. object of type foo. Here is how to use these functions:
  665.  
  666. > (make-foo)
  667. #s(FOO BAR NIL BAAZ NIL QUUX NIL) 
  668. > (make-foo :baaz 3)
  669. #s(FOO BAR NIL BAAZ 3 QUUX NIL) 
  670. > (foo-bar *)
  671. NIL
  672. > (foo-baaz **)
  673. 3
  674.  
  675. The make-foo function can take a keyword argument for each of the
  676. fields a structure of type foo can have. The field access functions
  677. each take one argument, a structure of type foo, and return the
  678. appropriate field.
  679.  
  680. See below for how to set the fields of a structure.
  681.  
  682.  
  683.  
  684. Setf
  685.  
  686. Certain forms in LISP naturally define a memory location. For example,
  687. if the value of x is a structure of type foo, then (foo-bar x) defines
  688. the bar field of the value of x. Or, if the value of y is a one-
  689. dimensional array, (aref y 2) defines the third element of y.
  690.  
  691. The setf special form uses its first argument to define a place in
  692. memory, evaluates its second argument, and stores the resulting value
  693. in the resulting memory location. For example,
  694.  
  695. > (setq a (make-array 3))
  696. #(NIL NIL NIL)
  697. > (aref a 1)
  698. NIL
  699. > (setf (aref a 1) 3)
  700. 3
  701. > a
  702. #(NIL 3 NIL)
  703. > (aref a 1)
  704. 3
  705. > (defstruct foo bar)
  706. FOO
  707. > (setq a (make-foo))
  708. #s(FOO :BAR NIL)
  709. > (foo-bar a)
  710. NIL
  711. > (setf (foo-bar a) 3)
  712. 3
  713. > a
  714. #s(FOO :BAR 3)
  715. > (foo-bar a)
  716. 3
  717.  
  718. Setf is the only way to set the fields of a structure or the elements
  719. of an array.
  720.  
  721. Here are some more examples of setf and related functions.
  722.  
  723. > (setf a (make-array 1))       ;setf on a variable is equivalent to setq
  724. #(NIL)
  725. > (push 5 (aref a 0))           ;push can act like setf
  726. (5)
  727. > (pop (aref a 0))              ;so can pop
  728. 5
  729. > (setf (aref a 0) 5)
  730. 5
  731. > (incf (aref a 0))             ;incf reads from a place, increments,
  732. 6                               ;and writes back
  733. > (aref a 0)
  734. 6
  735.  
  736.  
  737.  
  738. Booleans and Conditionals
  739.  
  740. LISP uses the self-evaluating symbol nil to mean false. Anything other
  741. than nil means true. Unless we have a reason not to, we usually use the
  742. self-evaluating symbol t to stand for true.
  743.  
  744. LISP provides a standard set of logical functions, for example and, or,
  745. and not. The and and or connectives are short-circuiting: and will not
  746. evaluate any arguments to the right of the first one which evaluates to
  747. nil, while or will not evaluate any arguments to the right of the first
  748. one which evaluates to t.
  749.  
  750. LISP also provides several special forms for conditional execution. The
  751. simplest of these is if. The first argument of if determines whether
  752. the second or third argument will be executed:
  753.  
  754. > (if t 5 6)
  755. 5
  756. > (if nil 5 6)
  757. 6
  758. > (if 4 5 6)
  759. 5
  760.  
  761. If you need to put more than one statement in the then or else clause
  762. of an if statement, you can use the progn special form. Progn executes
  763. each statement in its body, then returns the value of the final one.
  764.  
  765. > (setq a 7)
  766. 7
  767. > (setq b 0)
  768. 0
  769. > (setq c 5)
  770. 5
  771. > (if (> a 5)
  772.     (progn
  773.       (setq a (+ b 7))
  774.       (setq b (+ c 8)))
  775.     (setq b 4)
  776.   )
  777. 13
  778.  
  779. An if statement which lacks either a then or an else clause can be
  780. written using the when or unless special form:
  781.  
  782. > (when t 3)
  783. 3
  784. > (when nil 3)
  785. NIL
  786. > (unless t 3)
  787. NIL
  788. > (unless nil 3)
  789. 3
  790.  
  791. When and unless, unlike if, allow any number of statements in their
  792. bodies. (Eg, (when x a b c) is equivalent to (if x (progn a b c)).)
  793.  
  794. > (when t
  795.     (setq a 5)
  796.     (+ a 6)
  797.   )
  798. 11
  799.  
  800. More complicated conditionals can be defined using the cond special
  801. form, which is equivalent to an if ... else if ... fi construction.
  802.  
  803. A cond consists of the symbol cond followed by a number of cond
  804. clauses, each of which is a list. The first element of a cond clause is
  805. the condition; the remaining elements (if any) are the action. The cond
  806. form finds the first clause whose condition evaluates to true (ie,
  807. doesn't evaluate to nil); it then executes the corresponding action and
  808. returns the resulting value. None of the remaining conditions are
  809. evaluated; nor are any actions except the one corresponding to the
  810. selected condition. For example:
  811.  
  812. > (setq a 3)
  813. 3
  814. > (cond
  815.    ((evenp a) a)        ;if a is even return a
  816.    ((> a 7) (/ a 2))    ;else if a is bigger than 7 return a/2
  817.    ((< a 5) (- a 1))    ;else if a is smaller than 5 return a-1
  818.    (t 17)               ;else return 17
  819.   )
  820. 2
  821.  
  822. If the action in the selected cond clause is missing, cond returns what
  823. the condition evaluated to:
  824.  
  825. > (cond ((+ 3 4)))
  826. 7
  827.  
  828. Here's a clever little recursive function which uses cond. You might be
  829. interested in trying to prove that it terminates for all integers x at
  830. least 1. (If you succeed, please publish the result.)
  831.  
  832. > (defun hotpo (x steps)        ;hotpo stands for Half Or Triple Plus One
  833.     (cond
  834.      ((= x 1) steps)
  835.      ((oddp x) (hotpo (+ 1 (* x 3)) (+ 1 steps)))
  836.      (t (hotpo (/ x 2) (+ 1 steps)))
  837.   ) )
  838. A
  839. > (hotpo 7 0)
  840. 16
  841.  
  842. The LISP case statement is like a C switch statement:
  843.  
  844. > (setq x 'b)
  845. B
  846. > (case x
  847.    (a 5)
  848.    ((d e) 7)
  849.    ((b f) 3)
  850.    (otherwise 9)
  851.   )
  852. 3
  853.  
  854. The otherwise clause at the end means that if x is not a, b, d, e, or
  855. f, the case statement will return 9.
  856.  
  857.  
  858.  
  859. Iteration
  860.  
  861. The simplest iteration construct in LISP is loop: a loop construct
  862. repeatedly executes its body until it hits a return special form. For
  863. example,
  864.  
  865. > (setq a 4)
  866. 4
  867. > (loop 
  868.    (setq a (+ a 1))
  869.    (when (> a 7) (return a))
  870.   )
  871. 8
  872. > (loop
  873.    (setq a (- a 1))
  874.    (when (< a 3) (return))
  875.   )
  876. NIL
  877.  
  878. The next simplest is dolist: dolist binds a variable to the elements of
  879. a list in order and stops when it hits the end of the list.
  880.  
  881. > (dolist (x '(a b c)) (print x))
  882. NIL 
  883.  
  884. Dolist always returns nil. Note that the value of x in the above
  885. example was never nil: the NIL below the C was the value that dolist
  886. returned, printed by the read-eval-print loop.
  887.  
  888. The most complicated iteration primitive is called do. A do statement
  889. looks like this:
  890.  
  891. > (do ((x 1 (+ x 1))
  892.        (y 1 (* y 2)))
  893.       ((> x 5) y)
  894.     (print y)
  895.     (print 'working)
  896.   )
  897. WORKING 
  898. WORKING 
  899. WORKING 
  900. WORKING 
  901. 16 
  902. WORKING 
  903. 32 
  904.  
  905. The first part of a do specifies what variables to bind, what their
  906. initial values are, and how to update them. The second part specifies a
  907. termination condition and a return value. The last part is the body. A
  908. do form binds its variables to their initial values like a let, then
  909. checks the termination condition. As long as the condition is false, it
  910. executes the body repeatedly; when the condition becomes true, it
  911. returns the value of the return-value form.
  912.  
  913. The do* form is to do as let* is to let.
  914.  
  915.  
  916.  
  917. Non-local Exits
  918.  
  919. The return special form mentioned in the section on iteration is an
  920. example of a nonlocal return. Another example is the return-from form,
  921. which returns a value from the surrounding function:
  922.  
  923. > (defun foo (x)
  924.     (return-from foo 3)
  925.     x
  926.   )
  927. FOO
  928. > (foo 17)
  929. 3
  930.  
  931. Actually, the return-from form can return from any named block -- it's
  932. just that functions are the only blocks which are named by default. You
  933. can create a named block with the block special form:
  934.  
  935. > (block foo
  936.     (return-from foo 7)
  937.     3
  938.   )
  939. 7
  940.  
  941. The return special form can return from any block named nil. Loops are
  942. by default labelled nil, but you can make your own nil-labelled blocks:
  943.  
  944. > (block nil
  945.     (return 7)
  946.     3
  947.   )
  948. 7
  949.  
  950. Another form which causes a nonlocal exit is the error form:
  951.  
  952. > (error "This is an error")
  953. Error: This is an error
  954.  
  955. The error form applies format to its arguments, then places you in the
  956. debugger.
  957.  
  958.  
  959.  
  960. Funcall, Apply, and Mapcar
  961.  
  962. Earlier I promised to give some functions which take functions as
  963. arguments. Here they are:
  964.  
  965. > (funcall #'+ 3 4)
  966. 7
  967. > (apply #'+ 3 4 '(3 4))
  968. 14
  969. > (mapcar #'not '(t nil t nil t nil))
  970. (NIL T NIL T NIL T)
  971.  
  972. Funcall calls its first argument on its remaining arguments.
  973.  
  974. Apply is just like funcall, except that its final argument should be a
  975. list; the elements of that list are treated as if they were additional
  976. arguments to a funcall.
  977.  
  978. The first argument to mapcar must be a function of one argument; mapcar
  979. applies this function to each element of a list and collects the
  980. results in another list.
  981.  
  982. Funcall and apply are chiefly useful when their first argument is a
  983. variable. For instance, a search engine could take a heuristic function
  984. as a parameter and use funcall or apply to call that function on a
  985. state description. The sorting functions described later use funcall
  986. to call their comparison functions.
  987.  
  988. Mapcar, along with nameless functions (see below), can replace many
  989. loops.
  990.  
  991.  
  992.  
  993. Lambda
  994.  
  995. If you just want to create a temporary function and don't want to
  996. bother giving it a name, lambda is what you need.
  997.  
  998. > #'(lambda (x) (+ x 3))
  999. #<Closure: #88b71ece>
  1000. > (funcall * 5)
  1001. 8
  1002.  
  1003. The combination of lambda and mapcar can replace many loops. For
  1004. example, the following two forms are equivalent:
  1005.  
  1006. > (do ((x '(1 2 3 4 5) (cdr x))
  1007.        (y nil))
  1008.       ((null x) (reverse y))
  1009.     (push (+ (car x) 2) y)
  1010.   )
  1011. (3 4 5 6 7)
  1012. > (mapcar #'(lambda (x) (+ x 2)) '(1 2 3 4 5))
  1013. (3 4 5 6 7)
  1014.  
  1015.  
  1016.  
  1017. Sorting
  1018.  
  1019. LISP provides two primitives for sorting: sort and stable-sort.
  1020.  
  1021. > (sort '(2 1 5 4 6) #'<)
  1022. (1 2 4 5 6)
  1023. > (sort '(2 1 5 4 6) #'>)
  1024. (6 5 4 2 1)
  1025.  
  1026. The first argument to sort is a list; the second is a comparison
  1027. function. The sort function does not guarantee stability: if there are
  1028. two elements a and b such that (and (not (< a b)) (not (< b a))), sort
  1029. may arrange them in either order. The stable-sort function is exactly
  1030. like sort, except that it guarantees that two equivalent elements
  1031. appear in the sorted list in the same order that they appeared in the
  1032. original list.
  1033.  
  1034. Be careful: sort is allowed to destroy its argument, so if the original
  1035. sequence is important to you, make a copy with the copy-list or copy-seq
  1036. function.
  1037.  
  1038.  
  1039.  
  1040. Equality
  1041.  
  1042. LISP has many different ideas of equality. Numerical equality is
  1043. denoted by =. Two symbols are eq if and only if they are identical. Two
  1044. copies of the same list are not eq, but they are equal.
  1045.  
  1046. > (eq 'a 'a)
  1047. T
  1048. > (eq 'a 'b)
  1049. NIL
  1050. > (= 3 4)
  1051. T
  1052. > (eq '(a b c) '(a b c))
  1053. NIL
  1054. > (equal '(a b c) '(a b c))
  1055. T
  1056. > (eql 'a 'a)
  1057. T
  1058. > (eql 3 3)
  1059. T
  1060.  
  1061. The eql predicate is equivalent to eq for symbols and to = for numbers.
  1062.  
  1063. The equal predicate is equivalent to eql for symbols and numbers. It is
  1064. true for two conses if and only if their cars are equal and their cdrs
  1065. are equal. It is true for two structures if and only if the structures
  1066. are the same type and their corresponding fields are equal.
  1067.  
  1068.  
  1069.  
  1070. Some Useful List Functions
  1071.  
  1072. These functions all manipulate lists.
  1073.  
  1074. > (append '(1 2 3) '(4 5 6))    ;concatenate lists
  1075. (1 2 3 4 5 6)
  1076. > (reverse '(1 2 3))            ;reverse the elements of a list
  1077. (3 2 1)
  1078. > (member 'a '(b d a c))        ;set membership -- returns the first tail
  1079. (A C)                           ;whose car is the desired element
  1080. > (find 'a '(b d a c))          ;another way to do set membership
  1081. A
  1082. > (find '(a b) '((a d) (a d e) (a b d e) ()) :test #'subsetp)
  1083. (A B D E)                       ;find is more flexible though
  1084. > (subsetp '(a b) '(a d e))     ;set containment
  1085. NIL
  1086. > (intersection '(a b c) '(b))  ;set intersection
  1087. (B)
  1088. > (union '(a) '(b))             ;set union
  1089. (A B)
  1090. > (set-difference '(a b) '(a))  ;set difference
  1091. (B)
  1092.  
  1093. Subsetp, intersection, union, and set-difference all assume that each
  1094. argument contains no duplicate elements -- (subsetp '(a a) '(a b b)) is
  1095. allowed to fail, for example.
  1096.  
  1097. Find, subsetp, intersection, union, and set-difference can all take a
  1098. :test keyword argument; by default, they all use eql.
  1099.  
  1100.