-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathUB Lisp.htm
3116 lines (2853 loc) · 105 KB
/
UB Lisp.htm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!--
(in-package :user)
-->
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>UB Lisp</title>
</head>
<body alink="#FF0000" bgcolor="#FFFFFF" link="blue" text="#000000" vlink="maroon">
<font face="Arial, Helvetica, sans-serif">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody><tr align="left" bgcolor="#003366" valign="middle">
<th nowrap="nowrap" valign="top">
<div align="right">
<a href="http://www.buffalo.edu/">
<font color="#FFFFFF" face="Arial, Helvetica, sans-serif" size="2">
<i>UNIVERSITY AT BUFFALO - STATE UNIVERSITY OF NEW YORK</i>
</font></a></div>
</th>
</tr>
<tr align="right" valign="top">
<td nowrap="nowrap" valign="top">
<b>
<font color="#000000" face="Arial, Helvetica, sans-serif">
The Department of Computer Science & Engineering</font><br>
<a href="http://www.cse.buffalo.edu/"><img src="UB%20Lisp_files/cselogo.htm" alt="cse@buffalo" align="top" border="0" height="82" width="256"></a>
</b>
</td>
</tr>
</tbody></table>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody><tr bgcolor="003366" valign="middle">
<td align="right" nowrap="nowrap" width="50%">
<div align="left">
<i><b><a href="http://www.cse.buffalo.edu/%7Eshapiro/"><font color="#FFFFFF" face="Arial,Helvetica,sans-serif" size="4">STUART C. SHAPIRO</font></a><font color="#FFFFFF" face="Arial,Helvetica,sans-serif" size="4">: Lisp Short
Course</font></b></i></div>
</td>
<td align="right" width="50%"><img src="UB%20Lisp_files/blbinary.htm" align="absmiddle" height="25" width="150"></td>
</tr>
</tbody></table>
</font>
<p>
</p><center>
<h1>A Short Course in Common Lisp<br>
Summer, 2004<br>
<a href="http://www.cse.buffalo.edu/%7Eshapiro/">Stuart C. Shapiro</a>
& <a href="http://www.cse.buffalo.edu/%7Edrpierce/">David R. Pierce</a>
</h1>
</center>
<hr>
<p></p><center>Copyright © 2004 by Stuart C. Shapiro & David
R. Pierce. All rights reserved.</center>
<p>
</p><dl>
<dt>Meeting time and place:
</dt><dd> MTh 10:30 - 11:30, Baldy 21
<p></p></dd><dt>Syllabus
</dt><dd>
<ol>
<li> Common Lisp Resources
<ul>
<li> <a href="http://www.franz.com/support/documentation/8.1/doc/">Index
to all Allegro CL version 8.1 symbols</a>
</li><li><a href="http://www.franz.com/support/documentation/8.1/ansicl/ansicl.htm">ANSI
Common Lisp</a>
</li><li>The <a href="http://www.lispworks.com/documentation/HyperSpec/Front/"><i>Common Lisp
HyperSpec</i></a>
</li><li> Stuart C. Shapiro, <a href="http://www.cse.buffalo.edu/%7Eshapiro/Commonlisp/"> <cite>Common
Lisp: An Interactive Approach</cite></a>, W. H. Freeman, New York,
1992.
</li><li>On-line <a href="http://www.cse.buffalo.edu/%7Eshapiro/Courses/CSE202/Notes/">Course
Notes</a> from CSE202 of Fall 2000 to accompany the book <a href="http://www.cse.buffalo.edu/%7Eshapiro/Commonlisp/"> <cite>Common Lisp: An Interactive
Approach</cite></a>. (Note: this course is not currently operating)
</li></ul>
<p></p></li><li> Common Lisp Development Environment
<dl>
<dt> For file preparation, testing, and debugging:
</dt><dd>
<ul>
<li><code>xemacs &</code>
</li><li>For sample initialization files see
the directory
<code>~shapiro/.xemacs/</code>, and, especially,
<code>~shapiro/.xemacs/init-for-ac.el</code>.
</li></ul>
</dd><dt>For file preparation:
</dt><dd>
<ol>
<li>Use a file extension of <code>.cl</code>
</li><li>Use Common Lisp mode
</li><li>See the Common Lisp mode commands by doing <code>C-h m</code>
</li></ol>
</dd><dt>For testing and debugging:
</dt><dd>
<ol>
<li><code>M-x run-acl</code>
</li><li>Answer all questions by entering <code>RET</code>
</li><li>See the Inferior Common Lisp mode commands by doing <code>C-h m</code>
</li></ol>
</dd></dl>
<p></p></li><li>Lisp Execution Style
<ul>
<li>Expression-oriented: Evaluate a series of expressions.
</li><li>Optionally take input from a file, then from standard-input.
</li><li>The Lisp Listener.
</li><li>The read-eval-print loop.
</li></ul>
<p></p></li><li>Numbers Числа
<ul>
<li>A number is an atom that evaluates to itself. Числа являются атомами, которые вычисляются сами в себя.
</li><li>Test read-eval-print loop<br> Попробуйте цикл чтение-выполнение-вывод
Really: Ну правда, всё просто:
<ol>
<li>Read Чтение
</li><li>Construct an object Создание объекта
</li><li>Evaluate the object Выполнение объекта
</li><li>Choose a printed representation Выбор текстового представления объекта
</li><li>Print Вывод
</li></ol>
</li><li>Two surprises: Два сюрприза:
<ol>
<li>bignums большие числа (bignums)
</li><li>ratios дроби (ratios)
</li></ol>
</li></ul>
<p></p></li><li>Non-Atomic Expressions Не атомные выражения
<ul>
<li>Cambridge prefix notation Кембриджская префиксная нотация
</li><li> See the HyperSpec section on <a href="http://www.lispworks.com/reference/HyperSpec/Body/12_aa.htm">Numeric Смотрите CLtL2ed раздел Числа
Operations</a> Операции
</li></ul>
<p></p></li><li>(X)Emacs' <code>*scratch*</code> buffer is in Lisp Interaction mode<br> (X)Emacs'овый буфер <code>*scratch* находится в режиме исполнения Лиспового кода</code><br>
Type <code>C-j</code> after a Lisp form. Нажмите Ctrl-j после Лисповой формы.
<p></p></li><li>Exiting:<br> Выход:
<code>(exit)</code> or <code>:ex</code> to the Lisp Listener. (exit) или :ex в Лисповом режиме.
<p></p></li><li>Booleans Булевы значения
<ul>
<li>Lisp's False is <code>nil</code>, an atom that evaluates to itself.<br> Лисповая Ложь это nil (пустой список) - атом, который вычисляется сам в себя.
Try it. Попробуйте бесплатно без смс.
<p></p></li><li>Lisp's True is <code>t</code>, an atom that evaluates to itself, Лисповая Истина это t (символ t) - атом, который вычисляется сам в себя. Любой другой Лисповый объект кроме nil, также является истиной.
<i>and every other Lisp object except</i> <code>nil</code>.
<p></p></li><li><a href="http://www.lispworks.com/reference/HyperSpec/Body/m_and.htm"><code>and</code></a> и (and)
and <a href="http://www.lispworks.com/reference/HyperSpec/Body/m_or.htm"><code>or</code></a> и или (or)
are Lisp <a href="http://www.lispworks.com/reference/HyperSpec/Body/03_ababb.htm">macro</a>s являются Лисповыми макросами
that take an arbitrary number of arguments, and do short-circuit которые принимают любое количество аргументов, и лениво их вычисляют
evaluations.<br> Try them for different numbers of arguments.<br> Try
them with zero arguments.<br> They return <code>t</code>,
<code>nil</code>, or the value of the last expression evaluated under
their control, <i>a theme in Lisp</i>.
</li></ul>
<p><font color="red">Exercise</font>: Start a file for Lisp source code.<br>
For now, just put some comments at the top saying what it's for.
</p><p></p></li><li>Comment Characters
<blockquote>
<table border="">
<tbody><tr><td><code>;</code></td><td>Rest of line</td><td>In line after code</td></tr>
<tr><td><code>;;</code></td><td>Entire line</td><td>Indent like code</td></tr>
<tr><td><code>;;;</code></td><td>Entire line</td><td>Start in column 1</td></tr>
<tr><td><code>#|...|#</code></td><td>Comment brackets</td><td>Use for
commenting-out code</td></tr>
</tbody></table>
</blockquote>
<p></p></li><li>Defining Functions
<ul>
<li>See the ANSI Common Lisp section on the <a href="http://www.franz.com/support/documentation/8.1/ansicl/dictentr/defun.htm"><code>defun</code></a>
macro
<p></p></li><li>Example
<blockquote>
<pre>(defun average (x y)
"Returns the average of the numbers x and y."
;; Doesn't round or truncate integers
(/ (+ x y) 2))
</pre>
</blockquote>
<p></p></li><li>Variables have lexical scope.
<p></p></li><li>Objects, not variables have type.
<br>Try
<code>(type-of <i>n</i>)</code> for various numbers,
<code><i>n</i></code><br>
<p></p></li><li>Load your file:<br>
<code>(load "<i>file-name</i>")</code> to Listener<br>
or <code>:ld <i>file-name</i></code> to Listener<br>
or <code>:cl <i>file-name</i></code> to Listener<br>
or <code>C-c C-b</code> in source file buffer<br>
or <code>C-u C-c C-b</code> in source file buffer<br>
<p>Then try:<br>
<code>(average </code> and then pause and look at the minibuffer<br>
<code>(average 5 7)</code><br>
<code>(average 5 8)</code><br>
<code>(float (average 5 8))</code>
</p><p></p></li><li><font color="red">Exercise</font>: Define <code>(discrim a b c)</code> to return the
square root of <code>b<sup>2</sup> - 4ac</code><br>
<code>(discrim 2 7 5)</code> should return <code>3.0</code>
<p></p></li><li>Surprise: Lisp functions can return multiple values<br>
Try <code>(floor 5.25)</code> and <code>(round 5.25)</code>
<p></p></li><li>Example
<blockquote>
<pre>(defun +- (x d)
"Returns x+d and x-d."
(values (+ x d)
(- x d)))
</pre>
</blockquote>
<p>Try: <code>(values)</code>
</p><p></p></li><li><font color="red">Exercise</font>: Using <code>discrim</code>, define <code>(quad-roots a b
c)</code> to return the two roots of the quadradic equation
<blockquote>
ax<sup>2</sup> + bx + c = 0
</blockquote>
namely, <code>(-b + sqrt(b<sup>2</sup> - 4ac))/2a</code>
and <code>(-b - sqrt(b<sup>2</sup> - 4ac))/2a</code><br><br>
<code>(quad-roots 2 7 5)</code>
should return <code>-1.0</code> and <code>-2.5</code>
</li></ul>
<p></p></li><li>Two-Branched Conditional
<blockquote>
<code>(<a href="http://www.franz.com/support/documentation/8.1/ansicl/dictentr/if.htm">if</a>
<i>test-form then-form [else-form]</i>)</code>
<p>Note: <code>if</code> is a <a href="http://www.lispworks.com/reference/HyperSpec/Body/03_ababa.htm">special
form</a>
</p><p>Example:
</p><pre>(defun fact (n)
"Returns the factorial of n."
(if (<= n 0)
1
(* n (fact (1- n)))))
</pre>
<p><font color="red">Exercise</font>: Define <code>(fibonacci n)</code> to return the n<sup>th</sup>
Fibonacci number: 1 1 2 3 5 8 13 ...
</p></blockquote>
<p></p></li><li>Tracing<br>
<code>(<a href="http://www.lispworks.com/reference/HyperSpec/Body/m_tracec.htm#trace">trace</a>
<i>function-name ... function-name</i>)</code> turns on tracing of the
named functions.<br> <code>(trace)</code> returns a list of the
functions being traced.<br> <code>(<a href="http://www.lispworks.com/reference/HyperSpec/Body/m_tracec.htm#trace">untrace</a>
<i>function-name ... function-name</i>)</code> turns off tracing of
the named functions.<br> <code>(untrace)</code> turns off all tracing.
<p>Typing <code>C-c t</code> when your cursor is over a function name,
either in Common Lisp mode or in Inferior Common Lisp mode, toggles
tracing of that function.
</p><p>ACL has a <a href="http://www.franz.com/support/documentation/8.1/doc/debugging.htm#tracer-1">ACL
trace facility</a> with more controls.
</p><p>Try tracing <code>discrim</code> and <code>quad-root</code>.<br>
Try tracing <code>fact</code> and/or <code>fibonacci</code>.<br>
Try these with the functions both interpreted and compiled.
</p></li><li>
<p>
Characters
</p>
<ul>
<li>
<p>
<a href="http://www.lispworks.com/reference/HyperSpec/Body/13_.htm">Characters</a>,
like numbers, are "self-evaluating atoms". Their
syntax is <tt>#\</tt><i><name of character></i>.
Try these:
</p>
<blockquote>
<pre>#\a
#\space
#\newline
</pre>
</blockquote>
</li>
<li>
<p>
Lisp handles Unicode characters and character names.
</p>
<blockquote>
<pre>#\latin_small_letter_a
#\latin_small_letter_a_with_acute
#\latin_small_letter_eth
#\greek_capital_letter_sigma
</pre>
</blockquote>
<p>
Note that <tt>#\latin_small_letter_a</tt> is another
example of Lisp choosing a print syntax.
</p>
</li>
<li>
<p>
Now try this with each of the characters above:
</p>
<blockquote>
<pre>(format t "~a" #\latin_small_letter_a_with_acute)
</pre>
</blockquote>
<p>
<a href="http://www.lispworks.com/reference/HyperSpec/Body/f_format.htm#format"><tt>Format</tt></a>
is the Lisp equivalent of <tt>printf</tt>, only (MUCH!)
more powerful, of course. We will talk about format in
detail later, but for now, <tt>format t</tt> prints to
standard output, and <tt>~a</tt> is the control sequence
for printing in "human readable" format.
</p>
<p>
Lisp can represent Unicode characters, but Emacs will
only gracefull display the ones in the Latin-1 encoding
(á and ð). You can try others (e.g.,
<tt>#\greek_capital_letter_sigma</tt>) but Emacs won't
handle them as gracefully. However, you can see the
Unicode using <a href="http://www.lispworks.com/reference/HyperSpec/Body/f_char_c.htm#char-code"><tt>char-code</tt></a>:
</p>
<blockquote>
<pre>(char-code #\greek_capital_letter_sigma)
</pre>
</blockquote>
</li>
<li>
<p>
For character comparison, use <tt>char=</tt>,
<tt>char<</tt>, <tt>char></tt>.
</p>
</li>
<li>
<p>
See <a href="http://www.lispworks.com/reference/HyperSpec/Body/13_aa.htm">§13.1.1</a> for additional useful functions.
</p>
</li>
</ul>
</li>
<li>
<p>
Strings
</p>
<ul>
<li>
<p>
<a href="http://www.lispworks.com/reference/HyperSpec/Body/16_.htm">Strings</a>
are also self-evaluating atoms, denoted by a series of
characters between double quotes.
</p>
</li>
<li>
<p>
Constructing strings:
</p>
<blockquote>
<pre>"my string"
(char "my string" 0)
(char "my string" 2)
"string with \" in it"
(char "string with \" in it" 11)
(char "string with \" in it" 12)
(char "string with \" in it" 13)
(format t "~a" "string with \" in it")
(string #\latin_small_letter_a_with_acute)
(string-capitalize "david.r.pierce")
(string-trim "as" "sassafras")
</pre>
</blockquote>
</li>
<li>
<p>
Comparing strings:
</p>
<blockquote>
<pre>(string= "david pierce" "David Pierce")
(string-equal "david pierce" "David Pierce")
(string< "David Pierce" "Stu Shapiro")
(string/= "foobar" "foofoo")
</pre>
</blockquote>
</li>
<li>
<p>
Strings as sequences:
</p>
<blockquote>
<pre>(length "my string")
(length "\\")
(format t "~a" "\\")
(subseq "my string" 3)
(subseq "my string" 3 6)
(position #\space "my string")
(position #\i "David Pierce")
(position #\i "David Pierce" :start 5)
(search "pi" "david pierce and stu shapiro")
(search "pi" "david pierce and stu shapiro" :start2 10)
(concatenate 'string "foo" "bar")
(concatenate 'string
"d" (string #\latin_small_letter_a_with_grave)
"v" (string #\latin_small_letter_i_with_acute)
"d")
</pre>
</blockquote>
<p>
<a href="http://www.lispworks.com/reference/HyperSpec/Body/17_.htm">Sequences</a>
comprise several types that act as ordered containers of
elements (including lists and arrays as well as
strings). Each of these functions accepts sequence
arguments. We'll talk about sequences more later.
</p>
</li>
<li>
<p>
<font color="red">Exercise</font>: Define <tt>(string-1+
s)</tt> to construct a new string by adding 1 to the
character code of each character in its argument. For
example, <tt>(string-1+ "a b c") => "b!c!d"</tt>.
</p>
</li>
</ul>
<p></p></li><li>Symbols
<ul>
<li>A <a href="http://www.lispworks.com/reference/HyperSpec/Body/t_symbol.htm#symbol">symbol</a>
is an atom that might have a value, but might not.
</li><li><a href="http://www.lispworks.com/reference/HyperSpec/Body/02_cd.htm">Syntax</a>:
almost any sequence of characters (mixed case) that can't be
interpreted as a number.<br>
(Warning: In some older implementations, the Lisp reader upper-cases
all characters entered unless they're escaped.)
</li><li>Escape character: <code>\</code>
</li><li>Escape brackets: <code>| ... |</code>
</li><li>Attributes of a symbol
<ol>
<li><code>symbol-name</code>
</li><li><code>symbol-value</code>
</li><li><code>symbol-function</code>
</li><li><code>symbol-package</code>
</li><li><code>symbol-plist</code>
</li></ol>
</li><li>Quote: <code>'<i>expression</i></code> always evaluates to
<code><i>expression</i></code> rather than the value of
<code><i>expression</i></code>
<p></p></li><li>Load your source file with the definition of <code>average</code><br>
Try:
<pre>(type-of 'average)
(symbol-name 'average)
(type-of (symbol-name 'average))
(symbol-function 'average)
#'average
(type-of #'average)
(type-of (type-of #'average))
(function-lambda-expression #'average)
</pre>
<p> Load a compiled version of the file (e.g. with <code>C-c C-b</code>)<br>
Try:
</p><pre>#'average
(function-lambda-expression #'average)
</pre>
<p></p></li><li>Put your cursor in your <code>*common-lisp*</code> buffer, and
type <code>C-x 1</code> to expand it.<br>
Move your cursor over the symbol <code>average</code> in your
<code>*common-lisp*</code> buffer, and type <code>C-c .</code>
(Really type the dot.)
<p></p></li><li>Equality function for symbols, and identity in general: <a href="http://www.lispworks.com/reference/HyperSpec/Body/a_eql.htm#eql">eql</a><br>
Try it.
<p></p></li><li>How does the Lisp reader locate the symbol from what you type?
<ol>
<li>Read the characters you typed, and construct a string (the
symbol's name).
</li><li>Look up the atom from it's name in a "catalogue" (probably a hash table).
</li><li>If it's not there, create it, and put it there.
</li></ol>
<p>The process of installing a symbol in a catalogue is called
<i>interning</i> it,<br>
and a symbol that's been so installed is called an <i>interned symbol</i>.<br>
</p></li></ul>
<p></p></li><li>Packages
<p>A <a href="http://www.lispworks.com/reference/HyperSpec/Body/t_pkg.htm#package">package</a>
is a catalogue (map) of symbol name => symbol. I.e., a "name
space".<br>
There's always a current package which the Lisp reader uses to look up
symbol names.<br> Try typing <code>*package*</code> to the Lisp
Listener.
</p><p>Lisp packages have nothing to do with file directories or files, though
the usual style is to have a file "in" only one package.
</p><p> A symbol that's interned in a package may be <b>internal</b> or
<b>external</b> in that package, and that package is
considered the symbol's <b>home package</b>.<br>
Find the home package of a symbol by evaluating <code>(symbol-package
<i>symbol</i>)</code><br>
Try <code>(symbol-package 'average)</code> and <code>(symbol-package
'length)</code>
</p><p>Every package has a name, and may have one or more nicknames.<br>
Try: <code>(package-name (symbol-package 'average))</code><br>
and <code>(package-nicknames (symbol-package 'average))</code>
</p><p>Mappings between packages and their (nick)names:
</p><blockquote>
<code>(find-package <i>package-name-or-symbol</i>)</code><br>
<code>(package-name <i>package</i>)</code><br>
<code>(package-nicknames <i>package</i>)</code>
</blockquote>
<p>Evaluate <code>(describe 'average)</code> You should be able to
understand all or most of what's printed.
</p><p>Evaluate <code>(describe 'length)</code> Notice how many packages
there are.
</p><p> Put your cursor on a symbol in either the Lisp listener, or in a
file of Lisp source code, and type <code>C-c d</code>, then
<code>RET</code> in the minibuffer.
</p><p>Try <code>(documentation 'average 'function)</code>
</p><p>Symbol Completion: <code>C-c TAB</code>
</p><p>You can make a symbol external in its home package by <code><a href="http://www.franz.com/support/documentation/8.1/ansicl/dictentr/export.htm">export</a></code>ing
it.<br>
Try <code>(export 'average)</code><br>
Describe <code>average</code> again.
</p><p>You can change packages in the Lisp Listener by entering <code>:pa
<i>name-or-symbol</i></code><br> Try <code>:pa lisp</code> Note the
prompt.<br>
</p><p>You can refer to a symbol whose home package is <code>p</code> from
some other package whether or not it is external in <code>p</code>.<br>
To refer to an external symbol <code>s</code> in package
<code><i>p</i></code> type <code><i>p</i>:<i>s</i></code><br>
To refer to an internal symbol <code>s</code> in package
<code><i>p</i></code> type <code><i>p</i>::<i>s</i></code><br>
</p><p>Try:
</p><blockquote>
<pre>'cl-user::discrim
'cl-user::average
'cl-user:average
'cl-user::length
'discrim
</pre>
</blockquote>
Notice the printed representation Lisp chooses for these symbols.<br>
Notice that the last entry caused Lisp to create a symbol named
<code>"discrim"</code> in the <code>common-lisp</code> package.
<p> Enter <code>:pa user</code> to return to the
<code>common-lisp-user</code> package.<br>
</p><p>Try:
</p><blockquote>
<pre>'cl-user::discrim
'cl::discrim
(symbol-name 'discrim)
(symbol-name 'cl::discrim)
(string= (symbol-name 'discrim) (symbol-name 'cl::discrim))
(eql 'discrim 'cl::discrim)
</pre>
</blockquote>
It should not be confusing that <code>discrim</code> and
<code>cl::discrim</code> are two <i>different</i> symbols that have
the same name.
<p><b>Two Special Packages</b>
</p><ol>
<li>The Keyword Package
<p>Every symbol in the keyword package is external and evaluates to itself.<br>
It is entered with an empty package name and a single <code>:</code><br>
Try <code>(describe :foo)</code>
</p></li><li>The Non-Package
<p>If the reader reads <code>#:<i>s</i></code>, it will create an
<b>ininterned</b> symbol named <code>"<i>s</i>"</code>, i.e., one that
is not interned in any package.<br> An uninterned symbol can never by
found by the Lisp reader, and so will never be <code>eql</code> to any
separately read symbol, even one with the same name.
</p><p>Try:
</p><blockquote>
<pre>(describe '#:foo)
(eql '#:foo '#:foo)
(string= (symbol-name '#:foo) (symbol-name '#:foo))
</pre>
</blockquote>
Evaluate <code>(gensym)</code>. <code><a href="http://www.franz.com/support/documentation/8.1/ansicl/dictentr/gensym.htm">gensym</a></code> creates new uninterned symbols.
</li></ol>
<p><b>Defining Packages</b>
</p><p>The simplest way to define a package is by evaluating <code>(<a href="http://www.franz.com/support/documentation/8.1/ansicl/dictentr/defpacka.htm">defpackage</a>
<i>package-name</i>)</code>, where <code><i>package-name</i></code>,
which is not evaluated, is either a string, which will be the
package's name, or a symbol whose name will be used for the name of
the package. We recommend using a keyword symbol, such as
<code>(defpackage :test)</code>.
</p><p>Look at the xemacs buffer in which you've been putting the
exercises. Notice "<code>pkg:user</code>" in the mode line.
</p><p>Enter <code>(defpackage :test)</code> as the first form in this
file, right after your initial comments.
</p><p>We want the symbols in this file to be interned into the
<code>test</code> package. So, as the Lisp reader is reading this
file, we want to change the package to the <code>test</code> package
right after that package has been defined. We'll do this by calling
the <a href="http://www.franz.com/support/documentation/8.1/ansicl/dictentr/in-packa.htm"><code>in-package</code></a>
macro, which is what the Listener command <code>:pa</code> calls. The
<code>in-package</code> macro takes a string or symbol as its
argument, but doesn't evaluate it. We recommend using a symbol of the
keyword package, so put <code>(in-package :test)</code> right after
the <code>defpackage</code> form, and save the file.
</p><p>Notice the package in the mode line hasn't changed (yet). Kill the
buffer, and reload the file into xemacs. Notice that the package in
the mode line is correct. This is important, because that is the
package xemacs will use when you do <code>C-c C-b</code> or <code>C-u
C-c C-b</code>.
</p><p>Edit your file by changing "<code>:test</code>" to
"<code>:exercises</code>" in both places. Save the file. While your
cursor is still in the buffer containing the file, enter <code>M-x
fi:parse-mode-line-and-package</code>. (Use symbol completion.)
Notice that the package in the mode line has now been updated
properly.
</p><p>Xemacs sets the package of a buffer by finding the first occurrence
of a call to <code>in-package</code> in the file. You should not have
more than one call to <code>in-package</code> in any file.
</p><p><font color="red">Exercise</font>: Exit from Lisp, and rerun it.
Load your file of function definitions. What package is the Listener
now in? Test some of your functions.
</p><p>When Lisp loads a file, it stores the value of
<code>*package*</code>, and restores it after loading the file.
That's why you didn't have to call <code>in-package</code> after
loading the file to return to the <code>user</code> package.
</p><p><font color="red">Question</font>: Was the Lisp reader "in" the
<code>exercises</code> package when it read every form in your file?
</p><p>Make the symbols defining the functions in your
<code>exercises</code> package external by exporting them:<br>
Change the form
</p><blockquote>
<code>(defpackage :exercises)</code>
</blockquote>
to
<blockquote>
<pre>(defpackage :exercises
(:export #:average #:discrim #:fact #:quad-roots #:string-1+))
</pre>
</blockquote>
Save this version of the file, exit Lisp, run Lisp again, load your
source file, and try using the functions from the <code>user</code>
package.
<p><b>Using Packages</b>
</p><p>One package may <b>use</b> another package. In that case, in the
using package every exported symbol of the used package may be
referred to without a package qualifier.
</p><p>For example, the <code>common-lisp-user</code> package uses the
<code>common-lisp</code> package, which is why you can enter
<code>common-lisp</code> symbols such as
<code>common-lisp:length</code> without typing the package
qualifier.<br> To see this, evaluate <code>(package-use-list
:user)</code>.<br>
The <code>excl</code> package contains many symbols used in the
Allegro Common Lisp implementation that are not in the standard
<code>common-lisp</code> package, such as <code>excl:exit</code>.
</p><p>What packages does the <code>exercises</code> package use?<br>
Every package that's defined uses the <code>common-lisp</code> package
by default. This is important so that pre-defined Lisp functions may
be accessed easily.
</p><p>In the Lisp Listener, in the <code>user</code> package, evaluate
the form <code>(use-package :exercises)</code>. Now try using the
functions you've defined without the package qualifier.
</p><p>You may experiment on your own with defining a package and
explicitly listing other packages for it to use. If you explicitly
indicate any packages to use, you must explicitly list the
<code>common-lisp</code> package also.
</p><p><b>Shadowing Symbols</b>
</p><p><font color="red">Exercise</font>: In your exercises file, define
the function <code>last</code> to take a string and return its last
character.
</p><p>You can't, because <code>last</code> is the name of a function in
the <code>common-lisp</code> package, and you're not allowed to
redefine these functions. (Note: functions aren't in packages.
Reword that statement more carefully.)
</p><p>There are a lot of symbols in the <code>common-lisp</code> package.
Must you avoid all of them when naming your functions? No!
</p><p>Change the package in the Lisp Listener to the
<code>exercises</code> package, and shadow <code>cl:last</code> by
evaluating <code>(shadow 'last)</code>, and then type your definition
of last into the Listener. Test it.
</p><p>Add your definition of <code>last</code> to your source file, and
add the form <code>(:shadow cl:last)</code> to your
<code>defpackage</code> form. Also add your <code>last</code> symbol
to those being exported.
</p><p>Exit Lisp. Rerun it. Load your source file. Test your
<code>last</code> function.
</p><p>Try to have the <code>user</code> package use the
<code>exercises</code> package. There's a conflict. Only one symbol
with a given name may be accessible in any package without
qualification. You have to choose which one.
</p></li><li>
<p>
Lists and Conses
</p>
<p>
Lists are a fundamental data structure in Lisp, from which
the language derives its name (LISt Processing).
</p>
<p>
A list is an object that holds a sequence of elements, which
may be (references to) any Lisp objects. The syntax for
lists is (<i>a</i> <i>b</i> <i>c</i> ...). Lists are
created by <a href="http://www.lispworks.com/reference/HyperSpec/Body/f_list_.htm">list</a>.
</p>
<blockquote>
<pre>'()
'(1 2 3)
(list 1 2 3)
</pre>
</blockquote>
<p>
Notice what Lisp prints for <tt>'()</tt> -- <tt>nil</tt>.
The symbol <tt>nil</tt> also represents the empty list, as
well as false.
</p>
<p>
<font color="red">Exercise:</font> Construct the list
containing the two lists <tt>(1 2 3)</tt> and <tt>(4 5
6)</tt>.
</p>
<p>
Accessing elements:
</p>
<blockquote>
<pre>(first '(1 2 3))
(second '(1 2 3))
(third '(1 2 3))
(nth 5 '(1 2 3 4 5 6 7 8 9 10))
(rest '(1 2 3))
(rest (rest '(1 2 3)))
(nthcdr 0 '(1 2 3 4 5 6 7 8 9 10))
(nthcdr 5 '(1 2 3 4 5 6 7 8 9 10))
</pre>
</blockquote>
<p>
<a href="http://www.lispworks.com/reference/HyperSpec/Body/14_ab.htm">Working with lists</a>:
</p>
<blockquote>
<pre>(endp '())
(endp '(1 2 3))
(endp nil)
(endp ())
(listp '())
(listp '(1 2 3))
(eql '(1 2 3) '(1 2 3))
(equal '(1 2 3) '(1 2 3))
(length '(1 2 3))
(append '(1 2 3) '(4 5 6))
(member 3 '(1 2 3 4 5 6))
(last '(1 2 3 4 5 6))
(last '(1 2 3 4 5 6) 3)
(butlast '(1 2 3 4 5 6))
(butlast '(1 2 3 4 5 6) 3)
</pre>
</blockquote>
<p>
Lists are also <a href="http://www.lispworks.com/reference/HyperSpec/Body/17_a.htm">sequences</a>.
</p>
<p>
<font color="red">Exercise:</font> Write a function
<tt>(reverse l)</tt> which returns a list containing the
elements of list <i>l</i> in reverse order. (Common Lisp
already includes the <tt>reverse</tt> function, so you must
deal with the name conflict again.)
</p>
<p>
The basic building block of a list is called a "cons". A
cons is an object containing two elements. The elements are
called the <i>car</i> and the <i>cdr</i> (for historical
reasons). The syntax of a cons is (<i>car</i>
. <i>cdr</i>). You can picture a cons such as <tt>(1
. 2)</tt> as:
</p>
<blockquote>
<img src="UB%20Lisp_files/cons.htm">
</blockquote>
<p>
Conses are used to construct (linked) lists in the usual
way.
</p>
<blockquote>
<img src="UB%20Lisp_files/list.htm">
</blockquote>
<p>
When we use conses to implement lists, we will often refer
to the two elements as the <i>first</i> and the <i>rest</i>,
or the <i>head</i> and the <i>tail</i>. A list whose final
<i>cdr</i> is not the empty list <tt>()</tt> is called a
"dotted list" (e.g., <tt>(1 2 . 3)</tt>). A "proper list"
has <tt>()</tt> (i.e., <tt>nil</tt>) as its final
<i>cdr</i>. The function <tt>cons</tt> constructs cons
cells. Since lists are implemented using conses, it follows
that <tt>cons</tt> is also the function to add elements to
the front of a list.
</p>
<p>
Working with conses:
</p>
<blockquote>
<pre>(cons 1 2)
(cons 1 nil)
'(1 . nil)
(cons 1 '(2 3))
(consp '(1 . 2))
(car '(1 . 2))
(cdr '(1 . 2))
(first '(1 . 2))
(rest '(1 . 2))
</pre>
</blockquote>
<p>
Incidentally, conses can also be used to build binary trees.
</p>
<blockquote>
<img src="UB%20Lisp_files/tree.htm">
</blockquote>
<p>
<font color="red">Exercise</font>: Construct the binary tree
pictured above.
</p>
<p>
<font color="red">Exercise</font>: Define a function
<tt>(flatten2 binary-tree)</tt> that returns the list of
elements in <i>binary-tree</i> in order.
</p>
<p>
Moreover, proper lists can be used to build variable-arity
trees -- for example, ((a (b) c) (d ((e)) () f)).
</p>
</li>
<li>
<p>
One-Branch Conditionals
</p>
<p>
<a href="http://www.lispworks.com/reference/HyperSpec/Body/s_if.htm#if">If</a>
may be used without an <i>else</i> expression. In this
case, the <i>else</i> expression defaults to <tt>nil</tt>.
However, the preferred style in such a case is to use <a href="http://www.lispworks.com/reference/HyperSpec/Body/m_when_.htm#when">when</a>
and <a href="http://www.lispworks.com/reference/HyperSpec/Body/m_when_.htm#unless">unless</a>.
In particular, <tt>(when <i>test</i>
<i>expression</i>...)</tt> evaluates the <i>test</i> and, if
its result is true, evaluates the <i>expression</i>s in
order, using the result of the last expression as the final
result. If the test fails, the result is <tt>nil</tt>.
Similarly, <tt>(unless <i>test</i>
<i>expression</i>...)</tt> evaluates its expressions if the
result of the test is false.
</p>
<p>
Incidentally, many Lisp control structures -- like Lisp
programs -- allow a sequence of expressions and take their
result from the last expression. These include defun, when,
unless, and cond, which we will see next. Control
structures that do this are said in the language
specification to use an "implicit progn". Perhaps later
we'll mention where this terminology originates.
</p>
<p>
One-branch conditionals are particularly useful when the
default value of a computation is <tt>nil</tt>. For
example:
</p>
<blockquote>
<pre>(defun member (x list)
"Returns true if x is a member of list."
(when list
(or (eql x (first list)) (member x (rest list)))))
</pre>
</blockquote>
<p>
<font color="red">Exercise</font>: Write a function
<tt>(get-property x list)</tt> which returns the element of
<i>list</i> immediately following <i>x</i>, or <i>nil</i> if
<i>x</i> does not appear in <i>list</i>. For example,
<tt>(get-property 'name '(name david office 125)) =>
david</tt>. (You might take advantage of the fact that
Lisp's builtin <tt>member</tt> function does not just return
<tt>t</tt> when <i>x</i> is in the list. You can write this
without using <tt>when</tt>, but just for fun, use it
anyway.) A list of the form used by this function is
traditionally called a <a href="http://www.lispworks.com/reference/HyperSpec/Body/26_glo_p.htm#property_list">property
list</a>. Similar builtin functions are <a href="http://www.lispworks.com/reference/HyperSpec/Body/f_getf.htm#getf">getf</a> and <a href="http://www.lispworks.com/reference/HyperSpec/Body/f_get_pr.htm#get-properties">get-properties</a>,
although they take slightly different arrangements of
arguments.
</p>
</li>
<li>
<p>
Multi-Branch Conditionals
</p>
<p>
The form of the multi-branch conditional is:
</p>
<blockquote>
<pre>(cond
(<i>expression</i><sub>11</sub> <i>expression</i><sub>12</sub> ...)
(<i>expression</i><sub>21</sub> <i>expression</i><sub>22</sub> ...)
...
(<i>expression</i><sub>n1</sub> <i>expression</i><sub>n2</sub> ...))
</pre>
</blockquote>
<p>The <code><i>expression</i><sub>i1</sub></code> are evaluated
starting at <i>i = 1</i> until one of them evaluates to any
non-<code>null</code> value. If so, the rest of the expressions in
that group (if any) are evaluated, and the value of the last one
evaluated becomes the value of the <code>cond</code>. If all of the
<code><i>expression</i><sub>i1</sub></code> evaluate to
<code>nil</code>, then the value of the <code>cond</code> is
<code>nil</code>. As is often the case, the value of a Lisp
expression is the value of the last subexpression evaluated under its
control.
</p><p>Most frequently, <code>cond</code> is thought of as:
</p><blockquote>
<pre>(cond
(<i>test</i><sub>1</sub> <i>expression</i><sub>1</sub> ...)
(<i>test</i><sub>2</sub> <i>expression</i><sub>2</sub> ...)
...
(<i>test</i><sub>n</sub> <i>expression</i><sub>n</sub> ...))
</pre>
</blockquote>
<p>
The last <i>test</i> may be <tt>t</tt>, when it is to be
considered the default clause.
</p>