home *** CD-ROM | disk | FTP | other *** search
/ Amiga MA Magazine 1998 #6 / amigamamagazinepolishissue1998.iso / coders / jËzyki_programowania / clisp / doc / lisp-tutorial.txt < prev    next >
Lisp/Scheme  |  1977-12-31  |  30KB  |  1,132 lines

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