home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 36 Tips / 36-Tips.zip / lisp-tut.zip / LISP-Tut.inf (.txt) < prev    next >
OS/2 Help File  |  2000-07-15  |  30KB  |  1,139 lines

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