File size: 41,209 Bytes
7a045c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<html>
<head>
<title>LISP Tutorial Lecture 3: Data Abstraction</title>
</head>
<body bgcolor=ffffff>
<h1>LISP Tutorial Lecture 3: Data Abstraction</h1>

<h2>Binary Trees</h2>

<p>Suppose we want to create a new kind 
of <em>recursive data type</em>, our familiar binary trees.
The first thing we have to do is to define the data type in terms of
its <em>constructors</em>, <em>selectors</em> and <em>recognizers</em>.
In the case of binary trees, we have the following:
<ol>
<li><em>Constructors</em>:  We have two kinds of binary trees, <em>leaves</em>
        and <em>nodes</em>.  Accordingly, we need a constructor for each
        kind:
    <ul>
    <li><tt>(make-bin-tree-leaf <em>E</em>)</tt>: A leaf is a composite
        object with one component, the <em>element</em> <em>E</em>.
    <li><tt>(make-bin-tree-node <em>E</em> 
        <em>B1</em> <em>B2</em>)</tt>: A node consists of three components,
        an element <em>E</em>, a <em>left subtree</em> <em>B1</em> and
        a <em>right subtree</em> <em>B2</em>.  Each of <em>B1</em>
        and <em>B2</em> is a binary tree.
    </ul>
    Notice that the definition of binary tree is inherently recursive
    (as in the case of nodes).
    Larger binary trees can be composed from smaller ones.
<li><em>Selectors</em>:  We need to define a selector for each
    component of each kind of binary tree.
    <ul>
    <li><tt>(bin-tree-leaf-element <em>L</em>)</tt>: Retrieve the element
        of a leaf <em>L</em>.
    <li><tt>(bin-tree-node-element <em>N</em>)</tt>: Retrieve the element
        of a node <em>N</em>.
    <li><tt>(bin-tree-node-left <em>N</em>)</tt>: Retrieve the
        left subtree of a node <em>N</em>.
    <li><tt>(bin-tree-node-right <em>N</em>)</tt>: Retrieve the right
        subtree of a node <em>N</em>.
    </ul>
<li><em>Recognizers</em>:  We define one recognizer for each kind
    of binary tree.
    <ul>
    <li><tt>(bin-tree-leaf-p <em>B</em>)</tt>: Test if a given binary tree
        <em>B</em> is a leaf.
    <li><tt>(bin-tree-node-p <em>B</em>)</tt>: Test if a given binary tree
        <em>B</em> is a node.
    </ul>
</ol>

<p>Notice that we have not written a line of code yet, and still we
are able to write down the function signature of all the constructors,
selectors and recognizers.  The process is more or less mechanical:
<ol>
<li>Define a constructor for each variant of the recursive data type.
    The parameters for a constructor defines the components of
    a composite object.
<li>For each parameter of each constructor, define a selector to
    retrieve the corresponding component.
<li>For each constructor, define a corresponding recognizer.
</ol>

<p>The next question is how we are to <em>represent</em> a binary tree
as a LISP object.  Of course, a list is the first thing that comes to
our mind:
<ul>
<li>We represent an leaf with element <em>E</em> by a singleton list
    containing <em>E</em> (i.e. <tt>(list <em>E</em>)</tt>).
<li>A node with element <em>E</em>, left subtree <em>B1</em>
and right subtree <em>B2</em> is represented as a list containing
the three components (i.e.
<tt>(list <em>E</em> <em>B1</em> <em>B2</em>)</tt>).
</ul>
Fixing the representation, we can thus implement the recursive
data type functions:
<pre>
;;
;; Binary Trees
;;

;;
;; Constructors for binary trees
;;

(defun make-bin-tree-leaf (E)
  "Create a leaf."
  (list E))

(defun make-bin-tree-node (E B1 B2)
  "Create a node with element K, left subtree B1 and right subtree B2."
  (list E B1 B2))

;;
;; Selectors for binary trees
;;

(defun bin-tree-leaf-element (L)
  "Retrieve the element of a leaf L."
  (first L))

(defun bin-tree-node-element (N)
  "Retrieve the element of a node N."
  (first N))

(defun bin-tree-node-left (N)
  "Retrieve the left subtree of a node N."
  (second N))

(defun bin-tree-node-right (N)
  "Retrieve the right subtree of a node N."
  (third N))

;;
;; Recognizers for binary trees
;;

(defun bin-tree-leaf-p (B)
  "Test if binary tree B is a leaf."
  (and (listp B) (= (list-length B) 1)))

(defun bin-tree-node-p (B)
  "Test if binary tree B is a node."
  (and (listp B) (= (list-length B) 3)))
</pre>

<p>The representation scheme works out like the following:
<pre>
USER(5): (make-bin-tree-node '*
                             (make-bin-tree-node '+
                                                 (make-bin-tree-leaf 2)
                                                 (make-bin-tree-leaf 3))
                             (make-bin-tree-node '-
                                                 (make-bin-tree-leaf 7)
                                                 (make-bin-tree-leaf 8)))
(* (+ (2) (3)) (- (7) (8)))
</pre>
The expression above is a binary tree node with element <tt>*</tt> and
two subtrees.  The left subtree is itself a binary tree node with 
<tt>+</tt> as its element and leaves as its subtress.   The right
subtree is also a binary tree node with <tt>-</tt> as its element
and leaves as its subtrees.  All the leaves are decorated by
numeric components.
<pre>
            *
           / \
          /   \
         /     \
        +       -
       / \     / \
      2   3   7   8
</pre>

<h2>Searching Binary Trees</h2>

<p>As discussed in previous tutorials, having recursive data structures
defined in the way we did streamlines the process of formulating
structural recursions.  We review this concept in the following examples.

<p>Suppose we treat binary trees as containers.  An
expression <em>E</em> is a member of a binary tree <em>B</em> if:
<ol>
<li><em>B</em> is a leaf and its element is <em>E</em>.
<li><em>B</em> is a node and either its element is <em>E</em> or
    <em>E</em> is a member of one of its subtrees.
</ol>
For example, the definition asserts that the members of 
<tt>(* (+ (2) (3)) (- (7) (8)))</tt> are <tt>*</tt>, <tt>+</tt>,
<tt>2</tt>, <tt>3</tt>, <tt>-</tt>, <tt>7</tt> and <tt>8</tt>.
Such a definition can be directly implemented by our recursive data
type functions:
<pre>
(defun bin-tree-member-p (B E)
  "Test if E is an element in binary tree B."
  (if (bin-tree-leaf-p B)
      (equal E (bin-tree-leaf-element B))
    (or (equal E (bin-tree-node-element B))
        (bin-tree-member-p (bin-tree-node-left B) E)
	(bin-tree-member-p (bin-tree-node-right B) E))))
</pre>
The function can be made more readable by using the <tt>let</tt> form:
<pre>
(defun bin-tree-member-p (B E)
  "Test if E is an element in binary tree B."
  (if (bin-tree-leaf-p B)
      (equal E (bin-tree-leaf-element B))
    (let
	((elmt  (bin-tree-node-element B))
	 (left  (bin-tree-node-left    B))
	 (right (bin-tree-node-right   B)))
      (or (equal E elmt)
	  (bin-tree-member-p left E)
	  (bin-tree-member-p right E)))))
</pre>
<p>Tracing the execution of <tt>bin-tree-member-p</tt>, we get:
<pre>
USER(14): (trace bin-tree-member-p)
(BIN-TREE-MEMBER-P)
USER(15): (bin-tree-member-p '(+ (* (2) (3)) (- (7) (8))) 7) 
 0: (BIN-TREE-MEMBER-P (+ (* (2) (3)) (- (7) (8))) 7)
   1: (BIN-TREE-MEMBER-P (* (2) (3)) 7)
     2: (BIN-TREE-MEMBER-P (2) 7)
     2: returned NIL
     2: (BIN-TREE-MEMBER-P (3) 7)
     2: returned NIL
   1: returned NIL
   1: (BIN-TREE-MEMBER-P (- (7) (8)) 7)
     2: (BIN-TREE-MEMBER-P (7) 7)
     2: returned T
   1: returned T
 0: returned T
T
</pre>

<p><hr><b>Exercise:</b>
   Let <em>size(B)</em> be the number of members in a binary tree <em>B</em>.
   Give a recursive definition of <em>size(B)</em>, and then implement a
   LISP function <tt>(bin-tree-size <em>B</em>)</tt> that
   returns    <em>size(B)</em>.
<hr>



<h2>Traversing Binary Trees</h2>

<p>
Let us write a function 
that will <em>reverse</em> a tree in the sense that the left
and right subtrees of every node are swapped:
<pre>
(defun binary-tree-reverse (B)
  "Reverse binary tree B."
  (if (bin-tree-leaf-p B)
      B
    (let
	((elmt  (bin-tree-node-element B))
	 (left  (bin-tree-node-left    B))
	 (right (bin-tree-node-right   B)))
      (make-bin-tree-node elmt
		          (binary-tree-reverse right)
		          (binary-tree-reverse left)))))
</pre>
<p>The correctness of the above implementation can be articulated
as follows.  Given a binary tree <em>B</em> and an object <em>E</em>,
either the binary tree is a leaf or it is a node:
<ul>
<li><em>Case 1:</em> <em>B</em> is a leaf.<br>
    Then the reversal of <em>B</em> is simply <em>B</em> itself.
<li><em>Case 2:</em> <em>B</em> is a node.<br>
    Then <em>B</em> has three components, namely, an element <tt>elmt</tt>,
    a left subtree <tt>left</tt> and a right subtree <tt>right</tt>.
    The reversal of <em>B</em> is a node with element <tt>elmt</tt>,
    left subtree the reversal of <tt>right</tt>, and right subtree
    the reversal of <tt>left</tt>.
</ul>
<p>The following shows us how the recursion unfolds:
<pre>
USER(21): (trace bin-tree-reverse)
(BIN-TREE-REVERSE)
USER(22): (bin-tree-reverse '(* (+ (2) (3)) (- (7) (8))))
 0: (BIN-TREE-REVERSE (* (+ (2) (3)) (- (7) (8))))
   1: (BIN-TREE-REVERSE (- (7) (8)))
     2: (BIN-TREE-REVERSE (8))
     2: returned (8)
     2: (BIN-TREE-REVERSE (7))
     2: returned (7)
   1: returned (- (8) (7))
   1: (BIN-TREE-REVERSE (+ (2) (3)))
     2: (BIN-TREE-REVERSE (3))
     2: returned (3)
     2: (BIN-TREE-REVERSE (2))
     2: returned (2)
   1: returned (+ (3) (2))
 0: returned (* (- (8) (7)) (+ (3) (2)))
(* (- (8) (7)) (+ (3) (2)))
</pre>
The resulting expression represents the following tree:
<pre>
            *
           / \
          /   \
         /     \
        -       +
       / \     / \
      8   7   3   2
</pre>

<p>Let us implement a function that will extract the members of a given binary
tree, and put them into a list in preorder.
<pre>
(defun bin-tree-preorder (B)
  "Create a list containing keys of B in preorder."
  (if (bin-tree-leaf-p B)
      (list (bin-tree-leaf-element B))
    (let
	((elmt  (bin-tree-node-element B))
	 (left  (bin-tree-node-left    B))
	 (right (bin-tree-node-right   B)))
      (cons elmt
	    (append (bin-tree-preorder left)
		    (bin-tree-preorder right))))))
</pre>
Tracing the execution of the function, we obtain the following:
<pre>
USER(13): (trace bin-tree-preorder)
(BIN-TREE-PREORDER)
USER(14): (bin-tree-preorder '(* (+ (2) (3)) (- (7) (8))))
 0: (BIN-TREE-PREORDER (* (+ (2) (3)) (- (7) (8))))
   1: (BIN-TREE-PREORDER (+ (2) (3)))
     2: (BIN-TREE-PREORDER (2))
     2: returned (2)
     2: (BIN-TREE-PREORDER (3))
     2: returned (3)
   1: returned (+ 2 3)
   1: (BIN-TREE-PREORDER (- (7) (8)))
     2: (BIN-TREE-PREORDER (7))
     2: returned (7)
     2: (BIN-TREE-PREORDER (8))
     2: returned (8)
   1: returned (- 7 8)
 0: returned (* + 2 3 - 7 8)
(* + 2 3 - 7 8)
</pre>

<p>As we have discussed before, the <tt>append</tt> call in the code above
is a source of inefficiency that can be obtimized away:
<pre>
(defun fast-bin-tree-preorder (B)
  "A tail-recursive version of bin-tree-preorder."
  (preorder-aux B nil))

(defun preorder-aux (B A)
  "Append A to the end of the list containing elements of B in preorder."
  (if (bin-tree-leaf-p B)
      (cons (bin-tree-leaf-element B) A)
    (let
	((elmt  (bin-tree-node-element B))
	 (left  (bin-tree-node-left    B))
	 (right (bin-tree-node-right   B)))
      (cons elmt
	    (preorder-aux left
			  (preorder-aux right A))))))
</pre>
An execution trace of the implementation is the following:
<pre>
USER(15): (trace fast-bin-tree-preorder preorder-aux)          
(PREORDER-AUX FAST-BIN-TREE-PREORDER)
USER(16): (fast-bin-tree-preorder '(* (+ (2) (3)) (- (7) (8))))
 0: (FAST-BIN-TREE-PREORDER (* (+ (2) (3)) (- (7) (8))))
   1: (PREORDER-AUX (* (+ (2) (3)) (- (7) (8))) NIL)
     2: (PREORDER-AUX (- (7) (8)) NIL)
       3: (PREORDER-AUX (8) NIL)
       3: returned (8)
       3: (PREORDER-AUX (7) (8))
       3: returned (7 8)
     2: returned (- 7 8)
     2: (PREORDER-AUX (+ (2) (3)) (- 7 8))
       3: (PREORDER-AUX (3) (- 7 8))
       3: returned (3 - 7 8)
       3: (PREORDER-AUX (2) (3 - 7 8))
       3: returned (2 3 - 7 8)
     2: returned (+ 2 3 - 7 8)
   1: returned (* + 2 3 - 7 8)
 0: returned (* + 2 3 - 7 8)
(* + 2 3 - 7 8)
</pre>

<p><b>Exercise</b>: Implement a function that will create a list
containing members of a given binary tree in postorder.  Implement
also a tail-recursive version of the same function.

<p><b>Exercise</b>: Repeat the last exercise with inorder.

<h2>Abstract Data Types</h2>

<p><em>Abstract data types</em> are blackboxes.  They are defined
in terms of their external interfaces, and not their implementation.
For example, a <em>set</em> abstraction offers the following 
operations:
<ul>
<li><tt>(make-empty-set)</tt> creates an empty set.
<li><tt>(set-insert <em>S</em> <em>E</em>)</tt> 
    returns a set containing all members
    of set <em>S</em> plus an additional member <em>E</em>.
<li><tt>(set-remove <em>S</em> <em>E</em>)</tt>
    returns a set containing all members of set <em>S</em>
    except for <em>E</em>.
<li><tt>(set-member-p <em>S</em> <em>E</em>)</tt>
    returns true if <em>E</em> is a member of set <em>S</em>.
<li><tt>(set-empty-p <em>S</em>)</tt> returns true if set <em>S</em>
    is empty.
</ul>

<p>To implement an abstract data type, we need to decide on 
a representation.  Let us represent a set by a list with 
no repeated members.
<pre>
(defun make-empty-set ()
  "Creates an empty set."
  nil)

(defun set-insert (S E)
  "Return a set containing all the members of set S plus the element E."
  (adjoin E S :test #'equal))

(defun set-remove (S E)
  "Return a set containing all the members of set S except for element E."
  (remove E S :test #'equal))

(defun set-member-p (S E)
  "Return non-NIL if set S contains element E."
  (member E S :test #'equal))

(defun set-empty-p (S)
  "Return true if set S is empty."
  (null S))
</pre>

<p><hr><b>Exercise:</b>  Look up the definition of <tt>adjoin</tt>,
    <tt>remove</tt> and <tt>member</tt> from CLTL2.  In particular,
    find out how the <tt>:test</tt> keyword is used to specify
    the equality test function to be used by the three functions.
    What will happen if we omit the <tt>:test</tt> keyword and
    the subsequent <tt>#'equal</tt> when invoking the three
    functions?
<hr>

<p>Notice that we have implemented an abstract data type (sets)
using a more fundamental recursive data structure (lists) with additional
computational constraints (no repetition) imposed by the interface
functions.  

<h2>Binary Search Trees</h2>

<p>Another way of implementing the same set abstraction is to use
  the more efficient <em>binary search tree (BST)</em>.
Binary search trees are basically binary trees with the following
additional computational constraints:
<ul>
<li>All the members in the left subtree of a tree node
    is no greater than the element of the node.
<li>All the members in the right subtree of a tree node
    is greater than the element of the node.
<li>All the leaf members are distinct.
</ul>
Again, we are implementing an abstract data type (sets) by a more 
fundamental recursive data structure (binary trees) with additional
computational constraints.  In particular, we use the leaves of
a binary tree to store the member of a set, and the tree nodes
for providing indexing information that improves search performance.
for example, a BST representing the set {1 2 3 4} would look like:
<pre>
            2
           / \
          /   \
         /     \
        1       3
       / \     / \
      1   2   3   4
</pre>

<p> An
empty BST is represented by <tt>NIL</tt>, while a nonempty BST is
represented by a binary tree.
We begin with the constructor and recognizer for empty BST. 
<pre>
(defun make-empty-BST ()
  "Create an empty BST."
  nil)

(defun BST-empty-p (B)
  "Check if BST B is empty."
  (null B))
</pre>

<p>Given the additional computational constraints, membership test
can be implemented as follows:
<pre>
(defun BST-member-p (B E)
  "Check if E is a member of BST B."
  (if (BST-empty-p B)
      nil
    (BST-nonempty-member-p B E)))

(defun BST-nonempty-member-p (B E)
  "Check if E is a member of nonempty BST B."
  (if (bin-tree-leaf-p B)
      (= E (bin-tree-leaf-element B))
    (if (<= E (bin-tree-node-element B))
	(BST-nonempty-member-p (bin-tree-node-left B) E)
      (BST-nonempty-member-p (bin-tree-node-right B) E))))
</pre>
Notice that we handle the degenerate case of searching an empty BST
separately, and apply the well-known recursive search algorithm
only on nonempty BST.
<pre>
USER(16): (trace BST-member-p BST-nonempty-member-p)
(BST-NONEMPTY-MEMBER-P BST-MEMBER-P)
USER(17): (BST-member-p '(2 (1 (1) (2)) (3 (3) (4))) 3)
 0: (BST-MEMBER-P (2 (1 (1) (2)) (3 (3) (4))) 3)
   1: (BST-NONEMPTY-MEMBER-P (2 (1 (1) (2)) (3 (3) (4))) 3)
     2: (BST-NONEMPTY-MEMBER-P (3 (3) (4)) 3)
       3: (BST-NONEMPTY-MEMBER-P (3) 3)
       3: returned T
     2: returned T
   1: returned T
 0: returned T
T
</pre>

<p>Insertion is handled by the following family of functions:
<pre>
(defun BST-insert (B E)
  "Insert E into BST B."
  (if (BST-empty-p B)
      (make-bin-tree-leaf E)
    (BST-nonempty-insert B E)))

(defun BST-nonempty-insert (B E)
  "Insert E into nonempty BST B."
  (if (bin-tree-leaf-p B)
      (BST-leaf-insert B E)
    (let ((elmt  (bin-tree-node-element B))
	  (left  (bin-tree-node-left    B))
	  (right (bin-tree-node-right   B)))
      (if (<= E (bin-tree-node-element B))
	  (make-bin-tree-node elmt
			      (BST-nonempty-insert (bin-tree-node-left B) E)
			      right)
	(make-bin-tree-node elmt
			    left
			    (BST-nonempty-insert (bin-tree-node-right B) E))))))

(defun BST-leaf-insert (L E)
  "Insert element E to a BST with only one leaf."
  (let ((elmt (bin-tree-leaf-element L)))
    (if (= E elmt)
	L
      (if (< E elmt)
	  (make-bin-tree-node E
			      (make-bin-tree-leaf E)
			      (make-bin-tree-leaf elmt))
	(make-bin-tree-node elmt
			    (make-bin-tree-leaf elmt)
			    (make-bin-tree-leaf E))))))
</pre>
As before, recursive insertion to nonempty BST is handled 
outside of the general entry point of BST insertion.  Traversing
down the index nodes, the recursive algorithm eventually arrives
at a leaf.  In case the element is not already in the tree, the
leaf is turned into a node with leaf subtrees holding the inserted
element and the element of the original leaf.  For example, if
we insert 2.5 into the tree represented by 
<tt>(2 (1 (1) (2)) (3 (3) (4)))</tt>,
the effect is the following:
<pre>
            2                      2
           / \                    / \
          /   \                  /   \
         /     \       ==>      /     \
        1       3              1       3
       / \     / \            / \     / \
      1   2   3   4          1   2  2.5  4
                                    / \
                                  2.5  3
</pre>
A trace of the insertion operation is given below:
<pre>
USER(22): (trace BST-insert BST-nonempty-insert BST-leaf-insert)
(BST-LEAF-INSERT BST-NONEMPTY-INSERT BST-INSERT)
USER(23): (BST-insert '(2 (1 (1) (2)) (3 (3) (4))) 2.5)
 0: (BST-INSERT (2 (1 (1) (2)) (3 (3) (4))) 2.5)
   1: (BST-NONEMPTY-INSERT (2 (1 (1) (2)) (3 (3) (4))) 2.5)
     2: (BST-NONEMPTY-INSERT (3 (3) (4)) 2.5)
       3: (BST-NONEMPTY-INSERT (3) 2.5)
         4: (BST-LEAF-INSERT (3) 2.5)
         4: returned (2.5 (2.5) (3))
       3: returned (2.5 (2.5) (3))
     2: returned (3 (2.5 (2.5) (3)) (4))
   1: returned (2 (1 (1) (2)) (3 (2.5 (2.5) (3)) (4)))
 0: returned (2 (1 (1) (2)) (3 (2.5 (2.5) (3)) (4)))
(2 (1 (1) (2)) (3 (2.5 (2.5) (3)) (4)))
</pre>

<p>Removal of elements is handled by the following family of functions:
<pre>
(defun BST-remove (B E)
  "Remove E from BST B."
  (if (BST-empty-p B)
      B
    (if (bin-tree-leaf-p B)
	(BST-leaf-remove B E)
      (BST-node-remove B E))))

(defun BST-leaf-remove (L E)
  "Remove E from BST leaf L."
  (if (= E (bin-tree-leaf-element L))
      (make-empty-BST)
    L))

(defun BST-node-remove (N E)
  "Remove E from BST node N."
  (let
      ((elmt  (bin-tree-node-element N))
       (left  (bin-tree-node-left    N))
       (right (bin-tree-node-right   N)))
    (if (<= E elmt)
	(if (bin-tree-leaf-p left)
	    (if (= E (bin-tree-leaf-element left))
		right
	      N)
	  (make-bin-tree-node elmt (BST-node-remove left E) right))
      (if (bin-tree-leaf-p right)
	  (if (= E (bin-tree-leaf-element right))
	      left
	    N)
	(make-bin-tree-node elmt left (BST-node-remove right E))))))
</pre>
This time, removal from empty BST's and BST's with a single leaf are
both degenerate cases.  The recursive removal algorithm deals with
BST nodes.  Traversing down the index nodes, the recursive algorithm
searches for the parent node of the leaf to be removed.  In case it is
found, the sibling of the leaf to be removed replaces its parent
node.  For example, the effect of removing 2 from the BST represented 
by <tt>(2 (1 (1) (2)) (3 (3) (4)))</tt> is depicted as follows:
<pre>
            2                      2
           / \                    / \
          /   \                  /   \
         /     \       ==>      /     \
        1       3              1       4
       / \     / \            / \     
      1   2   3   4          1   2  
</pre>
A trace of the deletion operation is given below:
<pre>
USER(4): (trace BST-remove BST-node-remove)
(BST-NODE-REMOVE BST-REMOVE)
USER(5): (BST-remove '(2 (1 (1) (2)) (3 (3) (4))) 3)
 0: (BST-REMOVE (2 (1 (1) (2)) (3 (3) (4))) 3)
   1: (BST-NODE-REMOVE (2 (1 (1) (2)) (3 (3) (4))) 3)
     2: (BST-NODE-REMOVE (3 (3) (4)) 3)
     2: returned (4)
   1: returned (2 (1 (1) (2)) (4))
 0: returned (2 (1 (1) (2)) (4))
(2 (1 (1) (2)) (4))
</pre>

<p><hr><b>Exercise:</b> A set can be implemented as a <em>sorted list</em>,
which is a list storing distinct members in ascending order.  Implement
the sorted list abstraction.
<hr>

<h2>Polynomials</h2>

<p>We demonstrate how one can perform symbolic computation using
LISP.  To begin with, we define a new recursive data type for
<em>polynomials</em>, which is defined recursively as follows:
<ul>
<li>If <em>num</em> is a number, then
    <tt>(make-constant <em>num</em>)</tt> is a polynomial;
<li>If <em>sym</em> is a symbol, then <tt>(make-variable <em>sym</em>)</tt>
    is a polynomial;
<li>If <em>poly1</em> and <em>poly2</em> are polynomials, then
    the following are also polynomials: 
    <ul>
    <li><tt>(make-sum <em>poly1</em> <em>poly2</em>)</tt>
    <li><tt>(make-product <em>poly1</em> <em>poly2</em>)</tt>
    </ul>
<li>If <em>poly</em> is a polynomial and <em>num</em> is a number,
    then <tt>(make-power <em>poly</em> <em>num</em>)</tt> is a polynomial.
</ul>
One can represent polynomials in the most standard way:
<pre>
;;
;; Constructors for polynomials
;;

(defun make-constant (num)
  num)

(defun make-variable (sym)
  sym)

(defun make-sum (poly1 poly2)
  (list '+ poly1 poly2))

(defun make-product (poly1 poly2)
  (list '* poly1 poly2))

(defun make-power (poly num)
  (list '** poly num))
</pre>
For example, <tt>(make-power (make-sum (make-variable 'x) (make-constant 1)) 2)</tt> is represented by the LISP form <tt>(** (+ x 1) 2)</tt>, which
denotes the polynomail <em>(x + 1)<sup>2</sup></em> in our usual
notation.

<p>We then define a recognizer for each constructor:
<pre>
;;
;; Recognizers for polynomials
;;

(defun constant-p (poly)
  (numberp poly))

(defun variable-p (poly)
  (symbolp poly))

(defun sum-p (poly)
  (and (listp poly) (eq (first poly) '+)))

(defun product-p (poly)
  (and (listp poly) (eq (first poly) '*)))

(defun power-p (poly)
  (and (listp poly) (eq (first poly) '**)))
</pre>

<p>We then need to define selectors for the composite polynomials.
We define a selector for each component of each composite
constructor. 
<pre>
;;
;; Selectors for polynomials
;;

(defun constant-numeric (const)
  const)

(defun variable-symbol (var)
  var)

(defun sum-arg1 (sum)
  (second sum))

(defun sum-arg2 (sum)
  (third sum))

(defun product-arg1 (prod)
  (second prod))

(defun product-arg2 (prod)
  (third prod))

(defun power-base (pow)
  (second pow))

(defun power-exponent (pow)
  (third pow))
</pre>
One may ask why we define so many trivial looking functions for
carrying out the same task (<tt>sum-arg1</tt> and <tt>product-arg1</tt>
have exactly the same implementation).  The reason is that we 
may end up changing the representation in the future, and there is
no guarantee that sums and products will be represented similarly
in the future.  Also, programs written like this tends to be
self-commenting.

<p>Now that we have a completely defined polynomial data type, let us
do something interesting with it.  Let us define a function that 
carries out symbolic differentiation.  In particular, we want a function
<tt>(d <em>poly</em> <em>x</em>)</tt> which returns the derivative
of polynomial <em>poly</em> with respect to variable <em>x</em>.
Let us review our first-year differential calculus:
<ul>
<li>The derivative <em>(dC / dx)</em> of a constant <em>C</em>
     is zero.
<li>The derivative <em>(dy/dx)</em> of a variable <em>y</em>
    is 1 if the <em>x = y</em>.  Otherwise, we leave
    the derivative unevaluated.  We represent unevaluated 
    derivatives using the following functions
<pre>
;;
;; Unevaluated derivative
;;

(defun make-derivative (poly x)
    (list 'd poly x))

(defun derivative-p (poly x)
  (and (listp poly) (eq (first poly) 'd)))
</pre>
<li>The derivative <em>(d(F+G)/dx)</em>
   of a sum <em>(F+G)</em> is <em>(dF/dx) + (dG/dx)</em>.
<li>The derivative <em>(d(F*G)/dx)</em> of a product <em>(F*G)</em>
    is <em>F*(dG/dx) + G*(dF/dx)</em>.
<li>The derivative <em>(d(F<sup>N</sup>)/dx)</tt>
    of a power <em>F<sup>N</sup></em> is
    <em>N * F<sup>N-1</sup> * (dF/dx)</em>.
</ul>

<p>The above calculus can be encoded in LISP as follows:
<pre>
;;
;; Differentiation function
;;

(defun d (poly x)
  (cond
   ((constant-p poly) 0)
   ((variable-p poly) 
    (if (equal poly x) 
	1 
      (make-derivative poly x)))
   ((sum-p poly) 
    (make-sum (d (sum-arg1 poly) x) 
	      (d (sum-arg2 poly) x)))
   ((product-p poly) 
    (make-sum (make-product (product-arg1 poly) 
			    (d (product-arg2 poly) x))
	      (make-product (product-arg2 poly) 
			    (d (product-arg1 poly) x))))
   ((power-p poly)
    (make-product (make-product (power-exponent poly)
				(make-power (power-base poly) 
					    (1- (power-exponent poly))))
		  (d (power-base poly) x)))))
</pre>

<p>Test driving the differentiation function we get:
<pre>
USER(11): (d '(+ x y) 'x)
(+ 1 (D Y X))
USER(12): (d '(* (+ x 1) (+ x 1)) 'x)
(+ (* (+ X 1) (+ 1 0)) (* (+ X 1) (+ 1 0)))
USER(13): (d '(** (+ x 1) 2) 'x)
(* (* 2 (** (+ X 1) 1)) (+ 1 0))
</pre>

<p>The result is correct but very clumsy.  We would like to 
simplify the result a bit using the following rewriting rules:
<ul>
<li><em>E + 0 = E</em>
<li><em>0 + E = E</em>
<li><em>E * 0 = 0</em>
<li><em>0 * E = 0</em>
<li><em>E * 1 = E</em>
<li><em>1 * E = E</em>
<li><em>E<sup>0</sup> = 1</em>
<li><em>E<sup>1</sup> = E</em>
</ul>

<p>This can be done by defining a simplification framework, in which
we can implement such rules:
<pre>
;;
;; Simplification function
;;

(defun simplify (poly)
  "Simplify polynomial POLY."
  (cond
   ((constant-p poly) poly)
   ((variable-p poly) poly)
   ((sum-p poly)
    (let ((arg1 (simplify (sum-arg1 poly)))
	  (arg2 (simplify (sum-arg2 poly))))
      (make-simplified-sum arg1 arg2)))
   ((product-p poly)
    (let ((arg1 (simplify (product-arg1 poly)))
	  (arg2 (simplify (product-arg2 poly))))
      (make-simplified-product arg1 arg2)))
   ((power-p poly)
    (let ((base (simplify (power-base poly)))
	  (exponent (simplify (power-exponent poly))))
      (make-simplified-power base exponent)))
   ((derivative-p poly) poly)))
</pre>
The <tt>simplify</tt> function decomposes a composite polynomial into
its components, apply simplification recursively to the
components, and then invoke the type-specific simplification
rules (i.e. <tt>make-simplified-sum</tt>, <tt>make-simplified-product</tt>,
<tt>make-simplified-power</tt>) based on the type of the polynomial
being processed.

<p>The simplification rules are encoded in LISP as follows:
<pre>
(defun make-simplified-sum (arg1 arg2)
  "Given simplified polynomials ARG1 and ARG2, construct a simplified sum of ARG1 and ARG2."
  (cond
   ((and (constant-p arg1) (zerop arg1)) arg2)
   ((and (constant-p arg2) (zerop arg2)) arg1)
   (t                                    (make-sum arg1 arg2))))

(defun make-simplified-product (arg1 arg2)
  "Given simplified polynomials ARG1 and ARG2, construct a simplified product of ARG1 and ARG2."
  (cond
   ((and (constant-p arg1) (zerop arg1)) (make-constant 0))
   ((and (constant-p arg2) (zerop arg2)) (make-constant 0))
   ((and (constant-p arg1) (= arg1 1))   arg2)
   ((and (constant-p arg2) (= arg2 1))   arg1)
   (t                                    (make-product arg1 arg2))))

(defun make-simplified-power (base exponent)
  "Given simplified polynomials BASE and EXPONENT, construct a simplified power with base BASE and exponent EXPONENT."
  (cond
   ((and (constant-p exponent) (= exponent 1))   base)
   ((and (constant-p exponent) (zerop exponent)) (make-constant 1))
   (t                          (make-power base exponent))))
</pre>

<p>Let us see how all these pay off:
<pre>
USER(14): (simplify (d '(* (+ x 1) (+ x 1)) 'x))
(+ (+ X 1) (+ X 1))
USER(15): (simplify (d '(** (+ x 1) 2) 'x))
(* 2 (+ X 1))
</pre>
Comparing to the original results we saw before, this is a lot
more reasonable.

<p><hr><b>Exercise:</b> Extend the symbolic polynomial framework 
in the following ways:
<ul>
<li>Define a new type of polynomial --- <em>difference</em>.
    If <em>poly1</em> and <em>poly2</em> are polynomials, then
    <tt>(make-difference <em>poly1</em> <em>poly2</em>)</tt>
    is also a polynomial.  Implement the constructor, recognizer
    and selectors for this type of polynomial.
<li>The derivative <em>(d(F-G)/dx)</em> of a difference <em>(F-G)</em>
   is <em>(dF/dx) - (dG/dx)</em>.  Extend the differentiation function
   to incorporate this.
<li>Implement the following simplification rule:
    <ul>
    <li><em>E - 0 = E</em>
    </ul>
</ul>
<hr>

<p><hr><b>Exercise:</b> Extend the symbolic polynomial framework
in the following ways:
<ul>
<li>Define a new type of polynomial --- <em>negation</em>.
    If <em>poly1</em> is a polynomial, then <tt>(make-negation 
    <em>poly</em>)</tt> is also a polynomial.  Implement the
    constructor, recognizer and selectors for this type of polynomial.
<li>The derivative <em>(d(-F)/dx)</em> of a negation <em>-F</em>
    is <em>-(dF/dx)</em>.  Extend the differentiation function
    to incorporate this.
<li>Implement the following simplification rules:
    <ul>
    <li><em>-0 = 0</em>
    <li><em>-(-E) = E</em>
    </ul>
</ul>
<hr>

<p><hr><b>Exercise:</b> The simplification rules we have seen so 
far share a common feature: the right hand sides do not involve
any new polynomial constructor.  For example, <em>-(-E)</em> is 
simply <em>E</em>.  However, some of the most useful simplification
rules are those involving constructors on the right hand sides:
<ul>
<li><em>0 - E = -E</em>
<li><em>E<sub>1</sub> + (-E<sub>2</sub>) = E<sub>1</sub> - E<sub>2</sub></em>
<li><em>(-E<sub>1</sub>) + E<sub>2</sub> = E<sub>2</sub> - E<sub>1</sub></em>
<li><em>E<sub>1</sub> - (-E<sub>2</sub>) = E<sub>1</sub> + E<sub>2</sub></em>
<li><em>E * (-1) = -E</em>
<li><em>(-1) * E = -E</em>
</ul>
Within the type-specific simplification functions,
if we naively apply the regular constructors to build the expressions
on the right hand sides, then we run into the risk of constructing
polynomials that  are not fully simplified.  For example, <em>-x</em>
and <em>-1</em> are both fully simplified, but if we now construct their
product <em>(-1) * (-x)</em>, the last simplification rule above 
says that we can rewrite the product into <em>-(-x)</em>, which needs
further simplification.  One naive solution is to blindly apply full
simplification to the newly constructed polynomials, but this is
obviously an overkill.  What then is an efficient and yet correct
implementation of the
above simplification rules?
<hr>

<p><hr><b>Exercise:</b> If all the components of a composite polynomial
are constants, then we can actually perform further simplification.
For example, <tt>(+ 1 1)</tt> should be simplified to <tt>2</tt>.
Extend the simplification framework to incorporate this.
<hr>

<h2>Tower of Hanoi</h2>

<p>The Tower of Hanoi problem is a classical toy problem in 
Artificial Intelligence:  There are <em>N</em> disks 
<em>D<sub>1</sub></em>, <em>D<sub>2</sub></em>, ..., <em>D<sub>n</sub></em>,
of graduated sizes and three pegs 1, 2, and 3.  Initially all the disks
are stacked on peg 1, with <em>D<sub>1</sub></em>, the smallest,
on top and <em>D<sub>n</sub></em>, the largest, at the bottom.  The
problem is to transfer the stack to peg 3 given that only one disk
can be moved at a time and that no disk may be placed on top of a 
smaller one. [Pearl 1984]

<p>We call peg 1 the "from" peg, peg 3 the "to" peg.  Peg 2 is 
a actually a buffer to facilitate movement of disks, and we call
it an "auxiliary" peg.  We can move <em>N</em> disks from the
"from" peg to the "to" peg using the following recursive scheme.
<ol>
<li>Ignoring the largest disk at the "from" peg, treat the remaining disks
    as a Tower of Hanoi problem with <em>N-1</em> disks.  Recursively
    move the top <em>N-1</em> disks from the "from" peg to the
    "auxiliary" peg, using the "to" peg as a buffer.
<li>Now that the <em>N-1</em> smaller disks are in the "auxiliary" peg,
    we move the largest disk to the "to" peg.
<li>Ignoring the largest disk again, treat the remaining disks
    as a Tower of Hanoi problem with <em>N-1</em> disks.  
    Recursively move the <em>N-1</em> disks from the "auxiliary"
    peg to the "to" peg, using the "from" peg as a buffer.
</ol>

<p>To code this solution in LISP, we need to define some data structure.
First, we represent a disk by a number, so that <em>D<sub>i</sub></em>
is represented by <em>i</em>.
Second, we represent a stack of disks by a <em>tower</em>, which is
nothing but a list of numbers, with the first element representing
the top disk.  We define the usual constructors and selectors for
the tower data type.
<pre>
;;
;; A tower is a list of numbers
;;

(defun make-empty-tower ()
  "Create tower with no disk."
  nil)

(defun tower-push (tower disk)
  "Create tower by stacking DISK on top of TOWER."
  (cons disk tower))

(defun tower-top (tower)
  "Get the top disk of TOWER."
  (first tower))

(defun tower-pop (tower)
  "Remove the top disk of TOWER."
  (rest tower))
</pre>

<p>Third, we define the <em>hanoi</em> data type to represent
a Tower of Hanoi configuration.  In particular, a hanoi configuration
is a list of three towers.  The elementary constructors and selectors
are given below:
<pre>
;;
;; Hanoi configuration
;;

(defun make-hanoi (from-tower aux-tower to-tower)
  "Create a Hanoi configuration from three towers."
  (list from-tower aux-tower to-tower))

(defun hanoi-tower (hanoi i)
  "Select the I'th tower of a Hanoi construction."
  (nth (1- i) hanoi))
</pre>
<p>Working with towers within a Hanoi configuration is tedious.  
We therefore define some shortcut to capture recurring operations:
<pre>
;;
;; Utilities
;;

(defun hanoi-tower-update (hanoi i tower)
  "Replace the I'th tower in the HANOI configuration by tower TOWER."
  (cond
   ((= i 1) (make-hanoi tower (second hanoi) (third hanoi)))
   ((= i 2) (make-hanoi (first hanoi) tower (third hanoi)))
   ((= i 3) (make-hanoi (first hanoi) (second hanoi) tower))))

(defun hanoi-tower-top (hanoi i)
  "Return the top disk of the I'th tower in the HANOI configuration."
  (tower-top (hanoi-tower hanoi i)))

(defun hanoi-tower-pop (hanoi i)
  "Pop the top disk of the I'th tower in the HANOI configuration."
  (hanoi-tower-update hanoi i (tower-pop (hanoi-tower hanoi i))))

(defun hanoi-tower-push (hanoi i disk)
  "Push DISK into the I'th tower of the HANOI configuration."
  (hanoi-tower-update hanoi i (tower-push (hanoi-tower hanoi i) disk)))
</pre>

<p>The fundamental operator  we can perform on a Hanoi configuration
is to move a top disk from one peg to another:
<pre>
;;
;; Operator: move top disk from one tower to another
;;

(defun move-disk (from to hanoi)
  "Move the top disk from peg FROM to peg TO in configuration HANOI."
  (let
      ((disk               (hanoi-tower-top hanoi from))
       (intermediate-hanoi (hanoi-tower-pop hanoi from)))
    (hanoi-tower-push intermediate-hanoi to disk)))
</pre>

<p>We are now ready to capture the logic of our recursive solution
into the following code:
<pre>
;;
;; Subgoal: moving a tower from one peg to another
;;

(defun move-tower (N from aux to hanoi)
  "In the HANOI configuration, move the top N disks from peg FROM to peg TO using peg AUX as an auxiliary peg."
  (if (= N 1)
      (move-disk from to hanoi)
    (move-tower (- N 1) aux from to 
		(move-disk from to
			   (move-tower (- N 1) from to aux hanoi)))))
</pre>

<p>We use the driver function <tt>solve-hanoi</tt> to start up the recursion:
<pre>
;;
;; Driver function
;;

(defun solve-hanoi (N)
  "Solve the Tower of Hanoi problem."
  (move-tower N 1 2 3 (make-hanoi (make-complete-tower N) nil nil)))

(defun make-complete-tower (N)
  "Create a tower of N disks."
  (make-complete-tower-aux N (make-empty-tower)))

(defun make-complete-tower-aux (N A)
  "Push a complete tower of N disks on top of tower A."
  (if (zerop N)
      A
    (make-complete-tower-aux (1- N) (tower-push A N))))
</pre>

<p>To solve a Tower of Hanoi problem with 3 disks, we call
<tt>(solve-hanoi 3)</tt>:
<pre>
USER(50): (solve-hanoi 3)
(NIL NIL (1 2 3))
</pre>
All we get back is the final configuration, which is not as
interesting as knowing the sequence of moves taken by the
algorithm.  So we trace usage of the <tt>move-disk</tt>
operator:
<pre>
USER(51): (trace move-disk)
(MOVE-DISK)
USER(52): (solve-hanoi 3)
 0: (MOVE-DISK 1 3 ((1 2 3) NIL NIL))
 0: returned ((2 3) NIL (1))
 0: (MOVE-DISK 1 2 ((2 3) NIL (1)))
 0: returned ((3) (2) (1))
 0: (MOVE-DISK 3 2 ((3) (2) (1)))
 0: returned ((3) (1 2) NIL)
 0: (MOVE-DISK 1 3 ((3) (1 2) NIL))
 0: returned (NIL (1 2) (3))
 0: (MOVE-DISK 2 1 (NIL (1 2) (3)))
 0: returned ((1) (2) (3))
 0: (MOVE-DISK 2 3 ((1) (2) (3)))
 0: returned ((1) NIL (2 3))
 0: (MOVE-DISK 1 3 ((1) NIL (2 3)))
 0: returned (NIL NIL (1 2 3))
(NIL NIL (1 2 3))
</pre>
From the trace we can actually read off the sequence of
operator applications necessary for one to achieve the solution
configuration.
This is good, but not good enough.  We want to know why each move is
being taken.  So we trace also the high-level subgoals:
<pre>
USER(53): (trace move-tower)
(MOVE-TOWER)
USER(54): (solve-hanoi 3)
 0: (MOVE-TOWER 3 1 2 3 ((1 2 3) NIL NIL))
   1: (MOVE-TOWER 2 1 3 2 ((1 2 3) NIL NIL))
     2: (MOVE-TOWER 1 1 2 3 ((1 2 3) NIL NIL))
       3: (MOVE-DISK 1 3 ((1 2 3) NIL NIL))
       3: returned ((2 3) NIL (1))
     2: returned ((2 3) NIL (1))
     2: (MOVE-DISK 1 2 ((2 3) NIL (1)))
     2: returned ((3) (2) (1))
     2: (MOVE-TOWER 1 3 1 2 ((3) (2) (1)))
       3: (MOVE-DISK 3 2 ((3) (2) (1)))
       3: returned ((3) (1 2) NIL)
     2: returned ((3) (1 2) NIL)
   1: returned ((3) (1 2) NIL)
   1: (MOVE-DISK 1 3 ((3) (1 2) NIL))
   1: returned (NIL (1 2) (3))
   1: (MOVE-TOWER 2 2 1 3 (NIL (1 2) (3)))
     2: (MOVE-TOWER 1 2 3 1 (NIL (1 2) (3)))
       3: (MOVE-DISK 2 1 (NIL (1 2) (3)))
       3: returned ((1) (2) (3))
     2: returned ((1) (2) (3))
     2: (MOVE-DISK 2 3 ((1) (2) (3)))
     2: returned ((1) NIL (2 3))
     2: (MOVE-TOWER 1 1 2 3 ((1) NIL (2 3)))
       3: (MOVE-DISK 1 3 ((1) NIL (2 3)))
       3: returned (NIL NIL (1 2 3))
     2: returned (NIL NIL (1 2 3))
   1: returned (NIL NIL (1 2 3))
 0: returned (NIL NIL (1 2 3))
(NIL NIL (1 2 3))
</pre>
The trace gives us information as to what subgoals each operator
application is trying to establish.  For example, the top level
subgoals are the following:
<pre>
 0: (MOVE-TOWER 3 1 2 3 ((1 2 3) NIL NIL))
   1: (MOVE-TOWER 2 1 3 2 ((1 2 3) NIL NIL))
     ...
   1: returned ((3) (1 2) NIL)
   1: (MOVE-DISK 1 3 ((3) (1 2) NIL))
   1: returned (NIL (1 2) (3))
   1: (MOVE-TOWER 2 2 1 3 (NIL (1 2) (3)))
     ...
   1: returned (NIL NIL (1 2 3))
 0: returned (NIL NIL (1 2 3))
</pre>
They translate directly to the following:  In order to move a tower
of 3 disks from peg 1 to peg 3 using peg 2 as a buffer 
(i.e. <tt>(MOVE-TOWER 3 1 2 3 ((1 2 3) NIL NIL))</tt>)
we do the following:
<ol>
<li>
   "<tt>1: (MOVE-TOWER 2 1 3 2 ((1 2 3) NIL NIL))</tt>"<br>
   Move a tower of 2 disks from peg 1 to peg 2 using peg 3 as a buffer.
   The result of the move is the following:<br>
   "<tt>1: returned ((3) (1 2) NIL)</tt>"
<li>
   "<tt>1: (MOVE-DISK 1 3 ((3) (1 2) NIL))</tt>"<br>
   Move a top disk from peg 1 to peg 3.  The result of this move is:<br>
   "<tt>1: returned (NIL (1 2) (3))</tt>"<br>
<li>"<tt>1: (MOVE-TOWER 2 2 1 3 (NIL (1 2) (3)))</tt>"<br>
   Move a tower of 2 disks from peg 2 to peg 3 using peg 1 as a buffer,
   yielding the following configuration:<br>
   "<tt>1: returned (NIL NIL (1 2 3))</tt>"<br>
</ol>


</body>
</html>