File: LISP-tutorial.sgml

package info (click to toggle)
cmucl 20c-2
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 42,524 kB
  • sloc: lisp: 358,331; ansic: 28,385; asm: 3,777; sh: 1,236; makefile: 366; csh: 31
file content (1358 lines) | stat: -rw-r--r-- 36,323 bytes parent folder | download | duplicates (9)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
<!doctype linuxdoc system>

<article>

<title>Common LISP Hints

<author>Geoffrey J. Gordon &lt;ggordon@cs.cmu.edu&gt;
        Modified by Bruno Haible &lt;haible@ma2s2.mathematik.uni-karlsruhe.de&gt;
	and Peter Van Eynde &lt;s950045@uia.ua.ac.be&gt;

<date>Friday, February 5, 1993

<toc>
      
<sect> Note for other lisp's.

<p>
Note: This tutorial introduction to Common Lisp was written for the
CMU environment, so some of the details of running lisp toward the end
may differ from site to site.


<sect>Further Information

<p>
The best LISP textbook I know of is

  Guy L. Steele Jr. <em/Common LISP: the Language , The second edition/. Digital Press. 1990. Also called Cltl2.

The first edition is easier to read; the second describes a more recent
standard. (The differences between the two standards shouldn't affect
casual programmers.)

A book by Dave Touretsky has also been recommended to me, although I
haven't read it, so I can't say anything about it.



<sect>Symbols

<p>
A symbol is just a string of characters. There are restrictions on what
you can include in a symbol and what the first character can be, but as
long as you stick to letters, digits, and hyphens, you'll be safe.
(Except that if you use only digits and possibly an initial hyphen,
LISP will think you typed an integer rather than a symbol.) Some
examples of symbols:

<enum>
<item>    a
<item>        b
<item>        c1
<item>        foo
<item>        bar
<item>        baaz-quux-garply
</enum>

Some things you can do with symbols follow. (Things after a <tt/``&gt;''/ prompt
are what you type to the LISP interpreter, while other things are what
the LISP interpreter prints back to you. The <tt/``;''/ is LISP's comment
character: everything from a <tt/``;''/ to the end of line is ignored.)

<tscreen><verb>
> (setq a 5)            ;store a number as the value of a symbol
                        ;cmucl will print a warning, ignore it.
5
> a                     ;take the value of a symbol
5
> (let ((a 6)) a)       ;bind the value of a symbol temporarily to 6
6
> a                     ;the value returns to 5 once the let is finished
5
> (+ a 6)               ;use the value of a symbol as an argument to a function
11
> b                     ;try to take the value of a symbol which has no value
Error: Attempt to take the value of the unbound symbol B
                        ;or in CMUCL:
Error in KERNEL::UNBOUND-SYMBOL-ERROR-HANDLER:  the variable B is unbound.

Restarts:
  0: [ABORT] Return to Top-Level.

Debug  (type H for help)

(EVAL B)
0]
                        ; return to top-level by typing "0" or
                        ; "restart 0"               
</verb></tscreen>

There are two special symbols, <em/t/ and <em/nil/. The value of <tt/t/ is defined
always to be <tt/t/, and the value of <tt/nil/ is defined always to be <tt/nil/. LISP
uses <tt/t/ and <tt/nil/ to represent true and false. An example of this use is
in the if statement, described more fully later:

<tscreen><verb>
> (if t 5 6)
5
> (if nil 5 6)
6
> (if 4 5 6)
5
</verb></tscreen>

The last example is odd but correct: <tt/nil/ means false, and anything else
means true. (Unless we have a reason to do otherwise, we use <tt/t/ to mean
true, just for the sake of clarity.)

Symbols like <tt/t/ and <tt/nil/ are called self-evaluating symbols, because
they evaluate to themselves. There is a whole class of self-evaluating
symbols called keywords; any symbol whose name starts with a colon is a
keyword. (See below for some uses for keywords.) Some examples:

<tscreen><verb>
> :this-is-a-keyword
:THIS-IS-A-KEYWORD
> :so-is-this
:SO-IS-THIS
> :me-too
:ME-TOO
</verb></tscreen>

<sect>Numbers

<p>
An integer is a string of digits optionally preceded by + or -. A real
number looks like an integer, except that it has a decimal point and
optionally can be written in scientific notation. A rational looks like
two integers with a / between them. LISP supports complex numbers,
which are written <tt/&num;c(r i)/ (where r is the real part and i is the
imaginary part). A number is any of the above. Here are some numbers:

<enum>
<item>        5
<item>        17
<item>        -34
<item>        +6
<item>        3.1415
<item>        1.722e-15
<item>        &num;c(1.722e-15 0.75)
</enum>

The standard arithmetic functions are all available: <tt/+/, <tt/-/,
<tt/*/, <tt>/</tt>, <tt/floor/, 
<tt/ceiling/, <tt/mod/, <tt/sin/, <tt/cos/, <tt/tan/, <tt/sqrt/,
<tt/exp/, <tt/expt/, and so forth. All of them
accept any kind of number as an argument. <tt/+/, <tt/-/, <tt/*/, and
<tt>/</tt> return a
number according to type contagion: an integer plus a rational is a
rational, a rational plus a real is a real, and a real plus a complex
is a complex. Here are some examples:

<tscreen><verb>
> (+ 3 3/4)             ;type contagion
15/4 
> (exp 1)               ;e
2.7182817 
> (exp 3)               ;e*e*e
20.085537 
> (expt 3 4.2)          ;exponent with a base other than e
100.90418
> (+ 5 6 7 (* 8 9 10))  ;the fns +-*/ all accept multiple arguments
</verb></tscreen>

There is no limit to the absolute value of an integer except the memory
size of your computer. Be warned that computations with bignums (as
large integers are called) can be slow. (So can computations with
rationals, especially compared to the corresponding computations with
small integers or floats.)

<sect>Conses

<p>
A cons is just a two-field record. The fields are called ``car'' and
``cdr'', for historical reasons. (On the first machine where LISP was
implemented, there were two instructions <tt/CAR/ and <tt/CDR/ which stood for
"Contents of Address portion of Register" and ""Contents of Decrement 
portion of Register". Registers were twice as wide as the width of an
address, so you could have 2 adresses in one register. (sizeof(int)==
2*sizeof(void *) ) Conses were implemented using these two registers.)

Conses are easy to use:

<tscreen><verb>
> (cons 4 5)            ;Allocate a cons. Set the car to 4 and the cdr to 5.
(4 . 5)
                        ;you have just allocated memory and promptly
			;forgotten about it. In C this would cause 
                        ;a memory leak, but not in LISP.
> (cons (cons 4 5) 6)
((4 . 5) . 6)
> (car (cons 4 5))
4
> (cdr (cons 4 5))
5
</verb></tscreen>


<sect>Lists

<p>
You can build many structures out of conses. Perhaps the simplest is a
linked list: the car of each cons points to one of the elements of the
list, and the cdr points either to another cons or to <tt/nil/. You can
create such a linked list with the list fuction:

<tscreen><verb>
> (list 4 5 6)
(4 5 6)
</verb></tscreen>

Notice that LISP prints linked lists a special way: it omits some of
the periods and parentheses. The rule is: if the <tt/cdr/ of a cons is
<tt/nil/, 
LISP doesn't bother to print the period or the <tt/nil/; and if the
<tt/cdr/ of 
cons A is cons B, then LISP doesn't bother to print the period for cons
A or the parentheses for cons B. So:

<tscreen><verb>
> (cons 4 nil)
(4)
> (cons 4 (cons 5 6))
(4 5 . 6)
> (cons 4 (cons 5 (cons 6 nil)))
(4 5 6)
</verb></tscreen>

The last example is exactly equivalent to the call <tt/(list 4 5 6)/. Note
that <tt/nil/ now means the list with no elements: the cdr of (a b), a list
with 2 elements, is (b), a list with 1 element; and the cdr of (b), a
list with 1 element, is <tt/nil/, which therefore must be a list with no
elements.

The car and cdr of <tt/nil/ are defined to be nil.

If you store your list in a variable, you can make it act like a stack:

<tscreen><verb>
> (setq a nil)
NIL
> (push 4 a)
(4)
> (push 5 a)
(5 4)
> (pop a)
5
> a
(4)
> (pop a)
4
> (pop a)
NIL
> a
NIL
</verb></tscreen>


<sect>Functions

<p>
You saw one example of a function above. Here are some more:

<tscreen><verb>
> (+ 3 4 5 6)                   ;this function takes any number of arguments
18
> (+ (+ 3 4) (+ (+ 4 5) 6))     ;isn't prefix notation fun?
22
> (defun foo (x y) (+ x y 5))   ;defining a function
FOO
> (foo 5 0)                     ;calling a function
10
> (defun fact (x)               ;a recursive function
    (if (&gt; x 0) 
      (* x (fact (- x 1)))
      1
  ) )
FACT
> (fact 5)
120
> (defun a (x) (if (= x 0) t (b (- x))))        ;mutually recursive functions
A
> (defun b (x) (if (&gt; x 0) (a (- x 1)) (a (+ x 1))))
B
> (a 5)
T
> (defun bar (x)                ;a function with multiple statements in
    (setq x (* x 3))            ;its body -- it will return the value
    (setq x (/ x 2))            ;returned by its final statement
    (+ x 4))
BAR
> (bar 6)
13
</verb></tscreen>

When we defined <tt/foo/, we gave it two arguments, <tt/x/ and
<tt/y/. Now when we 
call <tt/foo/, we are required to provide exactly two arguments: the first
will become the value of <tt/x/ for the duration of the call to
<tt/foo/, and the 
second will become the value of <tt/y/ for the duration of the call. In
LISP, most variables are lexically scoped; that is, if <tt/foo/ calls <tt/bar/
and <tt/bar/ tries to reference <tt/x/, <tt/bar/ will not get
<tt/foo/'s value for <tt/x/. 

The process of assigning a symbol a value for the duration of some
lexical scope is called binding.

You can specify optional arguments for your functions. Any argument
after the symbol <tt/&amp;optional/ is optional:

<tscreen><verb>
> (defun bar (x &amp;optional y) (if y x 0))
BAR
> (defun baaz (&amp;optional (x 3) (z 10)) (+ x z))
BAAZ
> (bar 5)
0
> (bar 5 t)
5
> (baaz 5)
15
> (baaz 5 6)
11
> (baaz)
13
</verb></tscreen>

It is legal to call the function <tt/bar/ with either one or two arguments.
If it is called with one argument, <tt/x/ will be bound to the value of that
argument and <tt/y/ will be bound to <tt/nil/; if it is called with two
arguments, <tt/x/ and <tt/y/ will be bound to the values of the first
and second 
argument, respectively.

The function <tt/baaz/ has two optional arguments. It specifies a default
value for each of them: if the caller specifies only one argument, <tt/z/
will be bound to 10 instead of to <tt/nil/, and if the caller specifies no
arguments, <tt/x/ will be bound to 3 and <tt/z/ to 10.

You can make your function accept any number of arguments by ending its
argument list with an <tt/&amp;rest/ parameter. LISP will collect all arguments
not otherwise accounted for into a list and bind the <tt/&amp;rest/
parameter to 
that list. So:

<tscreen><verb>
> (defun foo (x &amp;rest y) y)
FOO
> (foo 3)
NIL
> (foo 4 5 6)
(5 6)
</verb></tscreen>

Finally, you can give your function another kind of optional argument
called a keyword argument. The caller can give these arguments in any
order, because they're labelled with keywords.

<tscreen><verb>
> (defun foo (&amp;key x y) (cons x y))
FOO
> (foo :x 5 :y 3)
(5 . 3)
> (foo :y 3 :x 5)
(5 . 3)
> (foo :y 3)
(NIL . 3)
> (foo)
(NIL)
</verb></tscreen>

An <tt/&amp;key/ parameter can have a default value too:

<tscreen><verb>
> (defun foo (&amp;key (x 5)) x)
FOO
> (foo :x 7)
7
> (foo)
5
</verb></tscreen>


<sect>Printing

<p>
Some functions can cause output. The simplest one is <tt/print/, which
prints its argument and then returns it.

<tscreen><verb>
> (print 3)
3
3
</verb></tscreen>

The first 3 above was printed, the second was returned.

If you want more complicated output, you will need to use <tt/format/.
Here's an example:

<tscreen><verb>
> (format t "An atom: &tilde;S&tilde;&percnt;and a list: &tilde;S&tilde;&percnt;and an integer: &tilde;D&tilde;&percnt;"
          nil (list 5) 6)
An atom: NIL
and a list: (5)
and an integer: 6
</verb></tscreen>

The first argument to format is either <tt/t/, <tt/nil/, or a
stream. <tt/T/ specifies 
output to the terminal. <tt/Nil/ means not to print anything but to return a
string containing the output instead. Streams are general places for
output to go: they can specify a file, or the terminal, or another
program. This handout will not describe streams in any further detail.

The second argument is a formatting template, which is a string
optionally containing formatting directives.

All remaining arguments may be referred to by the formatting
directives. LISP will replace the directives with some appropriate
characters based on the arguments to which they refer and then print
the resulting string.

Format always returns <tt/nil/ unless its first argument is <tt/nil/, in which
case it prints nothing and returns the string instead of printing it.

There are three different directives in the above example:
<tt/&tilde;S/, <tt/&tilde;D/, and 
<tt/&tilde;&percnt;/. The first one accepts any LISP object and is
replaced by a printed 
representation of that object (the same representation which is
produced by print). The second one accepts only integers. The third one
doesn't refer to an argument; it is always replaced by a carriage
return.

Another useful directive is <tt/&tilde;&tilde;/, which is replaced by
a single &tilde;. 

Refer to a LISP manual for (many, many) additional formatting
directives.



<sect>Forms and the Top-Level Loop

<p>
The things which you type to the LISP interpreter are called forms; the
LISP interpreter repeatedly reads a form, evaluates it, and prints the
result. This procedure is called the read-eval-print loop.

Some forms will cause errors. After an error, LISP will put you into
the debugger so you can try to figure out what caused the error. LISP
debuggers are all different; but most will respond to the command
"help" or ":help" by giving some form of help.

In general, a form is either an atom (for example, a symbol, an
integer, or a string) or a list. If the form is an atom, LISP evaluates
it immediately. Symbols evaluate to their value; integers and strings
evaluate to themselves. If the form is a list, LISP treats its first
element as the name of a function; it evaluates the remaining elements
recursively, and then calls the function with the values of the
remaining elements as arguments.

For example, if LISP sees the form <tt/(+ 3 4)/, it treats <tt/+/ as
the name of 
a function. It then evaluates 3 to get 3 and 4 to get 4; finally it
calls <tt/+/ with 3 and 4 as the arguments. The <tt/+/ function
returns 7, which 
LISP prints.

The top-level loop provides some other conveniences; one particularly
convenient convenience is the ability to talk about the results of
previously typed forms. LISP always saves its most recent three
results; it stores them as the values of the symbols <tt/*/, <tt/**/,
and <tt/***/. 
For example:

<tscreen><verb>
> 3
3
> 4
4
> 5
5
> ***
3
> ***
4
> ***
5
> **
4
> *
4
</verb></tscreen>


<sect>Special forms

<p>
There are a number of special forms which look like function calls but
aren't. These include control constructs such as <tt/if/ statements and do
loops; assignments like <tt/setq/, <tt/setf/, <tt/push/, and <tt/pop/;
definitions such as 
<tt/defun/ and <tt/defstruct/; and binding constructs such as
<tt/let/. (Not all of 
these special forms have been mentioned yet. See below.)

One useful special form is the <tt/quote/ form: <tt/quote/ prevents
its argument 
from being evaluated. For example:

<tscreen><verb>
> (setq a 3)
3
> a
3
> (quote a)
A
> 'a                    ;'a is an abbreviation for (quote a)
                        ;it's the quote next to the enter key
                        ;on a qwerty keyboard
A
</verb></tscreen>

Another similar special form is the <tt/function/ form: <tt/function/
causes its 
argument to be interpreted as a function rather than being evaluated.
For example:

<tscreen><verb>
> (setq + 3)
3
> +
3
> '+
+
> (function +)
#<Function + @ #x-fbef9de>
> #'+                   ;#'+ is an abbreviation for (function +)
#<Function + @ #x-fbef9de>
</verb></tscreen>

The <tt/function/ special form is useful when you want to pass a function as
an argument to another function. See below for some examples of
functions which take functions as arguments.

<sect>Binding

<p>
Binding is lexically scoped assignment. It happens to the variables in
a function's parameter list whenever the function is called: the formal
parameters are bound to the actual parameters for the duration of the
function call. You can bind variables anywhere in a program with the
let special form, which looks like this:

<tscreen><verb>
(let ((var1 val1)
      (var2 val2)
      ...
     )
    body)
</verb></tscreen>

(It's considered bad style to leave a single ``)'' on a line)

Let binds <tt/var1/ to <tt/val1/, <tt/var2/ to <tt/val2/, and so
forth; then it executes 
the statements in its body. The body of a let follows exactly the same
rules that a function body does. Some examples:

<tscreen><verb>
> (let ((a 3)) (+ a 1))
4
> (let ((a 2) 
        (b 3)
        (c 0))
    (setq c (+ a b))
    c)
5
> (setq c 4)
4                     ;and a warning from CMUCL, ignore it    
> (let ((c 5)) c)
5
> c
4
</verb></tscreen>

Instead of <tt/(let ((a nil) (b nil)) ...)/, you can write <tt/(let (a b) ...)/.

The <tt/val1/, <tt/val2/, etc. inside a let cannot reference the
variables <tt/var1/, 
<tt/var2/, etc. that the let is binding. For example,

<tscreen><verb>
> (let ((x 1)
        (y (+ x 1)))
    y)
Error: Attempt to take the value of the unbound symbol X
                      ;in CMUCL:

In: LET ((X 1) (Y (+ X 1)))
  (LET ((X 1) (Y #))
    Y)
Warning: Variable X defined but never used.


Warning: This variable is undefined:
  X

Error in KERNEL::UNBOUND-SYMBOL-ERROR-HANDLER:  the variable X is
unbound.

Restarts:
  0: [ABORT] Return to Top-Level.

Debug  (type H for help)

(EVAL::LEAF-VALUE
 #<C::REF #x9009B15  LEAF= #<C::GLOBAL-VAR #x9009AD5  NAME= X  KIND=
 :GLOBAL>>
 0
 #())
0]
</verb></tscreen>

If the symbol <tt/x/ already has a global value, stranger happenings will
result:

<tscreen><verb>
> (setq x 7)
7                     ;again a warning in CMUCL:
Warning:  Declaring X special.
                      ;x is automaticly declared special
> (let ((x 1)
        (y (+ x 1)))
    y
  )
8
</verb></tscreen>

The <tt/let*/ special form is just like <tt/let/ except that it allows
values to 
reference variables defined earlier in the <tt/let*/. For example,

<tscreen><verb>
> (setq x 7)
7
> (let* ((x 1)
         (y (+ x 1)))
    y
  )
2
</verb></tscreen>

The form

<tscreen><verb>
(let* ((x a)
       (y b))
       ...
) 
</verb></tscreen>

is equivalent to

<tscreen><verb>
(let ((x a))
     (let ((y b))
          ...
) )
</verb></tscreen>

<sect>Dynamic Scoping

<p>
The <tt/let/ and <tt/let*/ forms provide lexical scoping, which is what you
expect if you're used to programming in C or Pascal. Dynamic scoping is
what you get in BASIC: if you assign a value to a dynamically scoped
variable, every mention of that variable returns that value until you
assign another value to the same variable.

In LISP, dynamically scoped variables are called <em/special variables/. You
can declare a special variable with the defvar special form. Here are
some examples of lexically and dynamically scoped variables.

In this example, the function <tt/check-regular/ references a regular (ie,
lexically scoped) variable. Since <tt/check-regular/ is lexically outside of
the <tt/let/ which binds <tt/regular/, <tt/check-regular/ returns the
variable's global value.

<tscreen><verb>
> (set 'regular 5)    ;setq would make it special in CMUCL!
5 
> (defun check-regular () regular)
CHECK-REGULAR 
> (check-regular)
5 
> (let ((regular 6)) (check-regular))
5
</verb></tscreen>

In this example, the function <tt/check-special/ references a special (ie,
dynamically scoped) variable. Since the call to <tt/check-special/ is
temporally inside of the <tt/let/ which binds special,
<tt/check-special/ returns 
the variable's local value.

<tscreen><verb>
> (defvar *special* 5)
*SPECIAL*
> (defun check-special () *special*)
CHECK-SPECIAL
> (check-special)
5
> (let ((*special* 6)) (check-special))
6
</verb></tscreen>

By convention, the name of a special variable begins and ends with a *.
Special variables are chiefly used as global variables, since
programmers usually expect lexical scoping for local variables and
dynamic scoping for global variables.

For more information on the difference between lexical and dynamic
scoping, see <em/Common LISP: the Language/.


<sect>Arrays

<p>
The function <tt/make-array/ makes an array. The <tt/aref/ function
accesses its 
elements. All elements of an array are initially set to <tt/nil/. For
example:

<tscreen><verb>
> (make-array '(3 3))
#2a((NIL NIL NIL) (NIL NIL NIL) (NIL NIL NIL))
> (aref * 1 1)
NIL
> (make-array 4)        ;1D arrays don't need the extra parens
#(NIL NIL NIL NIL)
</verb></tscreen>

Array indices always start at 0.

See below for how to set the elements of an array.



<sect>Strings

<p>
A string is a sequence of characters between double quotes. LISP
represents a string as a variable-length array of characters. You can
write a string which contains a double quote by preceding the quote
with a backslash; a double backslash stands for a single backslash. For
example:

<tscreen><verb>
"abcd" has 4 characters
"\"" has 1 character
"\\" has 1 character
</verb></tscreen>

Here are some functions for dealing with strings:

<tscreen><verb>
> (concatenate 'string "abcd" "efg")
"abcdefg"
> (char "abc" 1)
#\b                     ;LISP writes characters preceded by #\
> (aref "abc" 1)
#\b                     ;remember, strings are really arrays
</verb></tscreen>

The <tt/concatenate/ function can actually work with any type of sequence:

<tscreen><verb>
> (concatenate 'string '(#\a #\b) '(#\c))
"abc"
> (concatenate 'list "abc" "de")
(#\a #\b #\c #\d #\e)
> (concatenate 'vector '#(3 3 3) '#(3 3 3))
#(3 3 3 3 3 3)
</verb></tscreen>


<sect>Structures

<p>
LISP structures are analogous to C structs or Pascal records. Here is
an example:

<tscreen><verb>
> (defstruct foo
    bar
    baaz
    quux)
FOO
</verb></tscreen>

This example defines a data type called <tt/foo/ which is a structure
containing 3 fields. It also defines 4 functions which operate on this
data type: <tt/make-foo/, <tt/foo-bar/, <tt/foo-baaz/, and
<tt/foo-quux/. The first one 
makes a new object of type <tt/foo/; the others access the fields of an
object of type <tt/foo/. Here is how to use these functions:

<tscreen><verb>
> (make-foo)
#s(FOO :BAR NIL :BAAZ NIL :QUUX NIL) 
> (make-foo :baaz 3)
#s(FOO :BAR NIL :BAAZ 3 :QUUX NIL) 
> (foo-bar *)
NIL
> (foo-baaz **)
3
</verb></tscreen>

The <tt/make-foo/ function can take a keyword argument for each of the
fields a structure of type <tt/foo/ can have. The field access functions
each take one argument, a structure of type <tt/foo/, and return the
appropriate field.

See below for how to set the fields of a structure.



<sect>Setf

<p>
Certain forms in LISP naturally define a memory location. For example,
if the value of <tt/x/ is a structure of type <tt/foo/, then
<tt/(foo-bar x)/ defines 
the <tt/bar/ field of the value of <tt/x/. Or, if the value of <tt/y/
is a one-dimensional array, <tt/(aref y 2)/ defines the third element
of <tt/y/. 

The <tt/setf/ special form uses its first argument to define a place in
memory, evaluates its second argument, and stores the resulting value
in the resulting memory location. For example,

<tscreen><verb>
> (setq a (make-array 3))
#(NIL NIL NIL)
> (aref a 1)
NIL
> (setf (aref a 1) 3)
3
> a
#(NIL 3 NIL)
> (aref a 1)
3
> (defstruct foo bar)
FOO
> (setq a (make-foo))
#s(FOO :BAR NIL)
> (foo-bar a)
NIL
> (setf (foo-bar a) 3)
3
> a
#s(FOO :BAR 3)
> (foo-bar a)
3
</verb></tscreen>

<tt/Setf/ is the only way to set the fields of a structure or the elements
of an array.

Here are some more examples of <tt/setf/ and related functions.

<tscreen><verb>
> (setf a (make-array 1))       ;setf on a variable is equivalent to setq
#(NIL)
> (push 5 (aref a 1))           ;push can act like setf
(5)
> (pop (aref a 1))              ;so can pop
5
> (setf (aref a 1) 5)
5
> (incf (aref a 1))             ;incf reads from a place, increments,
6                               ;and writes back
> (aref a 1)
6
</verb></tscreen>


<sect>Booleans and Conditionals

<p>
LISP uses the self-evaluating symbol <tt/nil/ to mean false. Anything other
than <tt/nil/ means true. Unless we have a reason not to, we usually use the
self-evaluating symbol <tt/t/ to stand for true.

LISP provides a standard set of logical functions, for example
<tt/and/, <tt/or/, 
and <tt/not/. The <tt/and/ and <tt/or/ connectives are
short-circuiting: and will not 
evaluate any arguments to the right of the first one which evaluates to
<tt/nil/, while <tt/or/ will not evaluate any arguments to the right
of the first 
one which evaluates to <tt/t/ (with <tt/t/ we mean here ``non-<tt/nil/'').

LISP also provides several special forms for conditional execution. The
simplest of these is <tt/if/. The first argument of <tt/if/ determines whether
the second or third argument will be executed:

<tscreen><verb>
> (if t 5 6)
5
> (if nil 5 6)
6
> (if 4 5 6)
5
</verb></tscreen>

If you need to put more than one statement in the then or else clause
of an if statement, you can use the <tt/progn/ special
form. <tt/Progn/ executes 
each statement in its body, then returns the value of the final one.

<tscreen><verb>
> (setq a 7)
7
> (setq b 0)
0
> (setq c 5)
5
> (if (&gt; a 5)
    (progn
      (setq a (+ b 7))
      (setq b (+ c 8)))
    (setq b 4))
13
</verb></tscreen>

An <tt/if/ statement which lacks either a then or an else clause can be
written using the <tt/when/ or <tt/unless/ special form:

<tscreen><verb>
> (when t 3)
3
> (when nil 3)
NIL
> (unless t 3)
NIL
> (unless nil 3)
3
</verb></tscreen>

<tt/When/ and <tt/unless/, unlike <tt/if/, allow any number of
statements in their 
bodies. (Eg, <tt/(when x a b c)/ is equivalent to 
<tt/(if x (progn a b c))/.)

<tscreen><verb>
> (when t
    (setq a 5)
    (+ a 6))
11
</verb></tscreen>

More complicated conditionals can be defined using the <tt/cond/ special
form, which is equivalent to an if ... else if ... fi construction.

A <tt/cond/ consists of the symbol <tt/cond/ followed by a number of cond
clauses, each of which is a list. The first element of a cond clause is
the condition; the remaining elements (if any) are the action. The cond
form finds the first clause whose condition evaluates to true (ie,
doesn't evaluate to nil); it then executes the corresponding action and
returns the resulting value. None of the remaining conditions are
evaluated; nor are any actions except the one corresponding to the
selected condition. For example:

<tscreen><verb>
> (setq a 3)
3
> (cond
   ((evenp a) a)        ;if a is even return a
   ((&gt; a 7) (/ a 2))    ;else if a is bigger than 7 return a/2
   ((&lt; a 5) (- a 1))    ;else if a is smaller than 5 return a-1
   (t 17))              ;else return 17
2
</verb></tscreen>

If the action in the selected cond clause is missing, <tt/cond/ returns what
the condition evaluated to:

<tscreen><verb>
> (cond ((+ 3 4)))
7
</verb></tscreen>

Here's a clever little recursive function which uses <tt/cond/. You might be
interested in trying to prove that it terminates for all integers <tt/x/ at
least 1. (If you succeed, please publish the result.)

<tscreen><verb>
> (defun hotpo (x steps)        ;hotpo stands for Half Or Triple Plus One
    (cond
     ((= x 1) steps)
     ((oddp x) (hotpo (+ 1 (* x 3)) (+ 1 steps)))
     (t (hotpo (/ x 2) (+ 1 steps)))))
A
> (hotpo 7 0)
16
</verb></tscreen>

The LISP case statement is like a C switch statement:

<tscreen><verb>
> (setq x 'b)
B
> (case x
   (a 5)
   ((d e) 7)
   ((b f) 3)
   (otherwise 9))
3
</verb></tscreen>

The otherwise clause at the end means that if <tt/x/ is not <tt/a/,
<tt/b/, <tt/d/, <tt/e/, or <tt/f/, the case statement will return 9.



<sect>Iteration

<p>
The simplest iteration construct in LISP is <tt/loop/: a <tt/loop/ construct
repeatedly executes its body until it hits a <tt/return/ special form. For
example,

<tscreen><verb>
> (setq a 4)
4
> (loop 
   (setq a (+ a 1))
   (when (&gt; a 7) (return a)))
8
> (loop
   (setq a (- a 1))
   (when (&lt; a 3) (return)))
NIL
</verb></tscreen>

The next simplest is <tt/dolist/: <tt/dolist/ binds a variable to the
elements of 
a list in order and stops when it hits the end of the list.

<tscreen><verb>
> (dolist (x '(a b c)) (print x))
A 
B 
C 
NIL 
</verb></tscreen>

<tt/Dolist/ always returns <tt/nil/. Note that the value of <tt/x/ in the above
example was never <tt/nil/: the<tt/ NIL/ below the C was the value
that <tt/dolist/ 
returned, printed by the read-eval-print loop.

The most complicated iteration primitive is called <tt/do/. A <tt/do/ statement
looks like this: 

<tscreen><verb>
> (do ((x 1 (+ x 1))
       (y 1 (* y 2)))
      ((&gt; x 5) y)
    (print y)
    (print 'working)
  )
1 
WORKING 
2 
WORKING 
4 
WORKING 
8 
WORKING 
16 
WORKING 
32 
</verb></tscreen>

The first part of a <tt/do/ specifies what variables to bind, what their
initial values are, and how to update them. The second part specifies a
termination condition and a return value. The last part is the body. A
do form binds its variables to their initial values like a <tt/let/, then
checks the termination condition. As long as the condition is false, it
executes the body repeatedly; when the condition becomes true, it
returns the value of the return-value form.

The <tt/do/* form is to <tt/do/ as <tt/let/* is to <tt/let/.



<sect>Non-local Exits

<p>
The <tt/return/ special form mentioned in the section on iteration is an
example of a nonlocal return. Another example is the <tt/return/-from form,
which returns a value from the surrounding function:

<tscreen><verb>
> (defun foo (x)
    (return-from foo 3)
    x)
FOO
> (foo 17)
3
</verb></tscreen>

Actually, the <tt/return-from/ form can return from any named block -- it's
just that functions are the only blocks which are named by default. You
can create a named block with the block special form:

<tscreen><verb>
> (block foo
    (return-from foo 7)
    3)
7
</verb></tscreen>

The <tt/return/ special form can return from any block named
<tt/nil/. Loops are 
by default labelled <tt/nil/, but you can make your own nil-labelled blocks:

<tscreen><verb>
> (block nil
    (return 7)
    3)
7
</verb></tscreen>

Another form which causes a nonlocal exit is the <tt/error/ form:

<tscreen><verb>
> (error "This is an error")
Error: This is an error
</verb></tscreen>

The <tt/error/ form applies format to its arguments, then places you in the
debugger.



<sect>Funcall, Apply, and Mapcar

<p>
Earlier I promised to give some functions which take functions as
arguments. Here they are:

<tscreen><verb>
> (funcall &num;'+ 3 4)
7
> (apply &num;'+ 3 4 '(3 4))
14
> (mapcar &num;'not '(t nil t nil t nil))
(NIL T NIL T NIL T)
</verb></tscreen>

<tt/Funcall/ calls its first argument on its remaining arguments.

<tt/Apply/ is just like <tt/funcall/, except that its final argument
should be a 
list; the elements of that list are treated as if they were additional
arguments to a <tt/funcall/.

The first argument to <tt/mapcar/ must be a function of one argument;
<tt/mapcar/ 
applies this function to each element of a list and collects the
results in another list.

<tt/Funcall/ and <tt/apply/ are chiefly useful when their first argument is a
variable. For instance, a search engine could take a heuristic function
as a parameter and use <tt/funcall/ or <tt/apply/ to call that function on a
state description. The sorting functions described later use <tt/funcall/
to call their comparison functions.

<tt/Mapcar/, along with nameless functions (see below), can replace many
loops.



<sect>Lambda

<p>
If you just want to create a temporary function and don't want to
bother giving it a name, <tt/lambda/ is what you need.

<tscreen><verb>
> #'(lambda (x) (+ x 3))
(LAMBDA (X) (+ X 3))
> (funcall * 5)               ;* is the last result,remember?
8
<tscreen><verb>

The combination of <tt/lambda/ and <tt/mapcar/ can replace many loops. For
example, the following two forms are equivalent:

<tscreen><verb>
> (do ((x '(1 2 3 4 5) (cdr x))
       (y nil))
      ((null x) (reverse y))
    (push (+ (car x) 2) y))
(3 4 5 6 7)
> (mapcar #'(lambda (x) (+ x 2)) '(1 2 3 4 5))
(3 4 5 6 7)
</verb></tscreen>

However the first version will run significantly faster when compiled
by CMUCL. But speed isn't everything and the second version is a lot
clearer and easier to debug.

<sect>Sorting

<p>
LISP provides two primitives for sorting: <tt/sort/ and <tt/stable-sort/.

<tscreen><verb>
> (sort '(2 1 5 4 6) #'<)
(1 2 4 5 6)
> (sort '(2 1 5 4 6) #'>)
(6 5 4 2 1)
</verb></tscreen>

The first argument to <tt/sort/ is a list; the second is a comparison
function. The <tt/sort/ function does not guarantee stability: if there are
two elements <tt/a/ and <tt/b/ such that <tt/(and (not (< a b)) (not
(< b a)))/, sort 
may arrange them in either order. The <tt/stable-sort/ function is exactly
like <tt/sort/, except that it guarantees that two equivalent elements
appear in the sorted list in the same order that they appeared in the
original list.

Be careful: <tt/sort/ is allowed to destroy its argument, so if the original
sequence is important to you, make a copy with the <tt/copy-list/ or
<tt/copy/-seq/ function.



<sect>Equality

<p>
LISP has many different ideas of equality. Numerical equality is
denoted by <tt/=/. Two symbols are <tt/eq/ if and only if they are
identical. Two 
copies of the same list are not <tt/eq/, but they are equal.

<tscreen><verb>
> (eq 'a 'a)
T
> (eq 'a 'b)
NIL
> (= 3 4)
T
> (eq '(a b c) '(a b c))
NIL
> (equal '(a b c) '(a b c))
T
> (eql 'a 'a)
T
> (eql 3 3)
T
</verb></tscreen>

The <tt/eql/ predicate is equivalent to <tt/eq/ for symbols and to
<tt/=/ for numbers. 

The <tt/equal/ predicate is equivalent to <tt/eql/ for symbols and
numbers. It is 
true for two conses if and only if their cars are equal and their cdrs
are equal. It is true for two structures if and only if the structures
are the same type and their corresponding fields are equal.



<sect>Some Useful List Functions

<p>
These functions all manipulate lists.

<tscreen><verb>
> (append '(1 2 3) '(4 5 6))    ;concatenate lists
(1 2 3 4 5 6)
> (reverse '(1 2 3))            ;reverse the elements of a list
(3 2 1)
> (member 'a '(b d a c))        ;set membership -- returns the first tail
(A C)                           ;whose car is the desired element
> (find 'a '(b d a c))          ;another way to do set membership
A
> (find '(a b) '((a d) (a d e) (a b d e) ()) :test #'subsetp)
(A B D E)                       ;find is more flexible though
> (subsetp '(a b) '(a d e))     ;set containment
NIL
> (intersection '(a b c) '(b))  ;set intersection
(B)
> (union '(a) '(b))             ;set union
(A B)
> (set-difference '(a b) '(a))  ;set difference
(B)
</verb></tscreen>

<tt/Subsetp/, <tt/intersection/, <tt/union/, and <tt/set-difference/
all assume that each 
argument contains no duplicate elements -- <tt/(subsetp '(a a) '(a b b))/ is
allowed to fail, for example.

<tt/Find/, <tt/subsetp/, <tt/intersection/, <tt/union/, and
<tt/set-difference/ can all take a
<tt/:test/ keyword argument; by default, they all use <tt/eql/.



<sect>Getting Started with Emacs

<p>
You can use Emacs to edit LISP code: most Emacses are set up to enter
LISP mode automatically when they find a file which ends in .lisp, but
if yours isn't, you can type <tt/M-x lisp-mode/. M-x means: meta-key
plus x. If there is a meta (or ALT) key try it. If this fails M-x can
be typed by typing ESC followed by x. If your keyboard lacks an ESC
key, curse DEC, and type control-&lsqb; followed by x.

You can run LISP under Emacs, too: make sure that there is a command in
your path called "lisp" which runs your favorite LISP. For example, you
could type

<tscreen><verb>
ln -s /usr/local/bin/clisp &tilde;/bin/lisp
</verb></tscreen>

This isn't needed in CMUCL. Lisp is called lisp there.

Then in Emacs type <tt/M-x run-lisp/. You can send LISP code to the LISP you
just started, and do all sorts of other cool things; for more
information, type <tt/C-h m/ from any buffer which is in LISP
mode. This means: press control <em/and/ h, release both and press m.

Actually, you don't even need to make a link. Emacs has a variable
called inferior-lisp-program; so if you add the line

<tscreen><verb>
(setq inferior-lisp-program "/usr/local/bin/clisp")
</verb></tscreen>

to your .emacs file, Emacs will know where to find CLISP when
you type <tt/M-x run-lisp/.


</article>