File size: 34,661 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
<html>
<head>
<title>LISP Tutorial 2: Advanced Functional Programming in LISP</title>
</head>
<body bgcolor=ffffff>
<h1>LISP Tutorial 2: Advanced Functional Programming in LISP</h1>

<h2>Auxiliary Functions and Accumulator Variables</h2>

<p>We define the <em>reversal</em> of a list <em>L</em>
to be a list containing exactly the elements of <em>L</em> in reversed
order.
The Common LISP  built-in function <tt>(reverse <em>L</em>)</tt>
returns the reversal of <em>L</em>:
<pre>
USER(1): (reverse '(1 2 3 4))
(4 3 2 1)
USER(2): (reverse '(1 (a b) (c d) 4))
(4 (c d) (a b) 1)
USER(3): (reverse nil)
NIL
</pre>

<p>Implementing a version of <tt>reverse</tt> is not difficult,
but finding an efficient implementation is not as trivial.
To review what we learned in the last tutorial, let us begin
with a naive implementation of <tt>reverse</tt>:
<pre>
(defun slow-list-reverse (L)
  "Create a new list containing the elements of L in reversed order."
  (if (null L)
      nil
    (list-append (slow-list-reverse (rest L)) 
                 (list (first L)))))
</pre>

<p>Notice that this linearly recursive implementation calls
the function <tt>list-append</tt> we implemented in the
the last tutorial.  Notice also the new function <tt>list</tt>,
which returns a list containing its arguments.  For example,
<tt>(list 1 2)</tt> returns the list <tt>(1 2)</tt>.  In general,
<tt>(list <em>x<sub>1</sub></em> <em>x<sub>2</sub></em> ... 
<em>x<sub>n</sub></em>)</tt>
is just a shorthand for <tt>(cons <em>x<sub>1</sub></em> 
(cons <em>x<sub>2</sub></em>
... (cons <em>x<sub>n</sub></em> nil) ... ))</tt>.  So, the expression
<tt>(list (first L))</tt> in the listing above returns a 
singleton list containing the first element of <tt>L</tt>.

<p>So, why does <tt>(slow-list-reverse <em>L</em>)</tt> returns
the reversal of <em>L</em>?  The list <em>L</em> is
constructed either by <tt>nil</tt> or by <tt>cons</tt>:
<ul>
<li><b>Case 1:</b> <em>L</em> is <tt>nil</tt>.<br>
  The reversal of 
 <em>L</em> is simply <tt>nil</tt>.
<li><b>Case 2:</b> <em>L</em> is constructed from a call to <tt>cons</tt>.<br>
  Then <tt>L</tt> has two components: <tt>(first <em>L</em>)</tt> and
<tt>(rest <em>L</em>)</tt>.  If we append <tt>(first <em>L</em>)</tt> 
to the end of the reversal of <tt>(rest <em>L</em>)</tt>,
then we
obtain the reversal of <em>L</em>.
Of course, we could make use of <tt>list-append</tt> to do this.
However, <tt>list-append</tt> expects two list arguments, so we
need to construct a singleton list containing <tt>(first <em>L</em>)</tt>
before we pass it as a second argument to <tt>list-append</tt>.
</ul>

<p>Let us trace the execution of the function to see how the recursive
calls unfold:
<pre>
USER(3): (trace slow-list-reverse)
(SLOW-LIST-REVERSE)
USER(4): (slow-list-reverse '(1 2 3 4))
 0: (SLOW-LIST-REVERSE (1 2 3 4))
   1: (SLOW-LIST-REVERSE (2 3 4))
     2: (SLOW-LIST-REVERSE (3 4))
       3: (SLOW-LIST-REVERSE (4))
         4: (SLOW-LIST-REVERSE NIL)
         4: returned NIL
       3: returned (4)
     2: returned (4 3)
   1: returned (4 3 2)
 0: returned (4 3 2 1)
(4 3 2 1)
</pre>
Everything looks fine, until we trace also the unfolding of <tt>list-append</tt>:
<pre>
USER(9): (trace list-append)
(LIST-APPEND)
USER(10): (slow-list-reverse '(1 2 3 4))
 0: (SLOW-LIST-REVERSE (1 2 3 4))
   1: (SLOW-LIST-REVERSE (2 3 4))
     2: (SLOW-LIST-REVERSE (3 4))
       3: (SLOW-LIST-REVERSE (4))
         4: (SLOW-LIST-REVERSE NIL)
         4: returned NIL
         4: (LIST-APPEND NIL (4))
         4: returned (4)
       3: returned (4)
       3: (LIST-APPEND (4) (3))
         4: (LIST-APPEND NIL (3))
         4: returned (3)
       3: returned (4 3)
     2: returned (4 3)
     2: (LIST-APPEND (4 3) (2))
       3: (LIST-APPEND (3) (2))
         4: (LIST-APPEND NIL (2))
         4: returned (2)
       3: returned (3 2)
     2: returned (4 3 2)
   1: returned (4 3 2)
   1: (LIST-APPEND (4 3 2) (1))
     2: (LIST-APPEND (3 2) (1))
       3: (LIST-APPEND (2) (1))
         4: (LIST-APPEND NIL (1))
         4: returned (1)
       3: returned (2 1)
     2: returned (3 2 1)
   1: returned (4 3 2 1)
 0: returned (4 3 2 1)
(4 3 2 1)
</pre>
What we see here is revealing: given a list of <em>N</em> element,
<tt>slow-list-reverse</tt> makes <em>O(N)</em> recursive calls, 
with each level of recursionl involving a call to the linear-time
function <tt>list-append</tt>.  The result is that <tt>slow-list-reverse</tt>
is an <em>O(N<sup>2</sup>)</em> function.

<p>We can in fact build a much more efficient version 
of <tt>reverse</tt> using <em>auxiliary functions</em>
and <em>accumulator variables</em>:
<pre>
(defun list-reverse (L)
  "Create a new list containing the elements of L in reversed order."
  (list-reverse-aux L nil))

(defun list-reverse-aux (L A)
  "Append list A to the reversal of list L."
  (if (null L)
      A
    (list-reverse-aux (rest L) (cons (first L) A))))
</pre>

<p>
The function <tt>list-reverse-aux</tt> is an <em>auxiliary function</em>
(or a <em>helper function</em>).  It does not perform any useful
function by itself, but the <em>driver function</em> 
<tt>list-reverse</tt> could use it as a tool when building a 
reversal.  Specifically, <tt>(list-reverse-aux <em>L</em> <em>A</em>)</tt>
returns a new list obtained by appending list <em>A</em> to
the reversal of list <em>L</em>.  By passing <tt>nil</tt> as <em>A</em>
to <tt>list-reverse-aux</tt>,
the driver function <tt>list-reverse</tt> obtains the reversal of <em>L</em>.

<p>Let us articulate why <tt>(list-reverse-aux <em>L</em> <em>A</em>)</tt> 
correctly appends <em>A</em> to the reversal of list <em>L</em>.
Again, we know that either
<em>L</em> is <tt>nil</tt> or it is constructed 
by <tt>cons</tt>:
<ul>
<li><b>Case 1:</b> <em>L</em> is <tt>nil</tt>.<br>
    The reversal of <em>L</em> is simply <tt>nil</tt>.  The
    result of appending <em>A</em> to the end of an empty list
    is simply <em>A</em> itself.
<li><b>Case 2:</b> <em>L</em> is constructed by <tt>cons</tt>.<br>
    Now <em>L</em> is composed of two parts: <tt>(first <em>L</em>)</tt>
    and <tt>(rest <em>L</em>)</tt>.  Observe that <tt>(first <em>L</em>)</tt>
    is the last element in the reversal of <em>L</em>.  If we are to
    append <em>A</em> to the end of the reversal of <em>L</em>, then
    <tt>(first <em>L</em>)</tt> will come immediately before the
    elements of <em>A</em>.  Observing the above, we recognize that
    we obtain the desired result by recursively appending
    <tt>(cons (first <em>L</em>) <em>A</em>)</tt> to the
    reversal of <tt>(rest <em>L</em>)</tt>. 
</ul>
Tracing both <tt>list-reverse</tt> and <tt>list-reverse-aux</tt>, we get
the following:
<pre>
USER(17): (trace list-reverse list-reverse-aux)
(LIST-REVERSE LIST-REVERSE-AUX)
USER(18): (list-reverse '(1 2 3 4))
 0: (LIST-REVERSE (1 2 3 4))
   1: (LIST-REVERSE-AUX (1 2 3 4) NIL)
     2: (LIST-REVERSE-AUX (2 3 4) (1))
       3: (LIST-REVERSE-AUX (3 4) (2 1))
         4: (LIST-REVERSE-AUX (4) (3 2 1))
           5: (LIST-REVERSE-AUX NIL (4 3 2 1))
           5: returned (4 3 2 1)
         4: returned (4 3 2 1)
       3: returned (4 3 2 1)
     2: returned (4 3 2 1)
   1: returned (4 3 2 1)
 0: returned (4 3 2 1)
(4 3 2 1)
</pre>
<p>For each recursive call to <tt>list-reverse-aux</tt>, notice how 
the first element of <em>L</em> is "peeled off", and is then 
"accumulated" in <em>A</em>.  Because of this observation, we
call the variable <em>A</em> an <em>accumulator variable</em>.

<h2>Factorial Revisited</h2>

<p>To better understand how auxiliary functions and accumulator 
variables are used, let us revisit the problem of computing
factorials.  The following is an alternative implementation
of the factorial function:
<pre>
(defun fast-factorial (N)
  "A tail-recursive version of factorial."
  (fast-factorial-aux N 1))

(defun fast-factorial-aux (N A)
  "Multiply A by the factorial of N."
  (if (= N 1)
      A
    (fast-factorial-aux (- N 1) (* N A))))
</pre>
Let us defer the explanation of why the function is named "<tt>fast-factorial</tt>", and treat it as just another way to implement <tt>factorial</tt>.
Notice the structural similarity between this pair of functions and
those for computing list reversal.  
The auxiliary function <tt>(fast-factorial-aux <em>N</em> <em>A</em>)</tt> 
computes the product of <em>A</em> and the <em>N</em>'th factorial.
The driver function computes <em>N!</em> by calling 
<tt>fast-factorial-aux</tt> with <em>A</em> set to 1.
Now, the correctness of the auxiliary function 
(i.e. that <tt>(fast-factorial-aux <em>N</em> <em>A</em>)</tt> indeed
returns the product of <em>N!</em> and <em>A</em>) can be established as
follows.  <em>N</em> is either one or larger than one.
<ul>
<li><em>Case 1</em>: <em>N = 1</em><br>
    The product of <em>A</em> and <em>1!</em> is simply <em>A * 1! = A</em>.
<li><em>Case 2</em>: <em>N > 1</em><br>
    Since <em>N! = N * (N-1)!</em>, we then have <em>N! * A = (N-1)! 
    * (N * A)</em>, thus justifying our implementation.
</ul>

<p>Tracing both <tt>fast-factorial</tt> and <tt>fast-factorial-aux</tt>,
   we get the following:
<pre>
USER(3): (trace fast-factorial fast-factorial-aux)  
(FAST-FACTORIAL-AUX FAST-FACTORIAL)
USER(4): (fast-factorial 4)
 0: (FAST-FACTORIAL 4)
   1: (FAST-FACTORIAL-AUX 4 1)
     2: (FAST-FACTORIAL-AUX 3 4)
       3: (FAST-FACTORIAL-AUX 2 12)
         4: (FAST-FACTORIAL-AUX 1 24)
         4: returned 24
       3: returned 24
     2: returned 24
   1: returned 24
 0: returned 24
24
</pre>

<p>If we compare the structure of <tt>fast-factorial</tt> with
<tt>list-reverse</tt>, we notice certain patterns underlying
the use of accumulator variables in auxiliary functions:
<ol>
<li>An auxiliary function generalizes the functionality of
    the driver function by promising to compute
    the function of interest and also combine the result with 
    the value of the accumulator variable.
    In the case of <tt>list-reverse-aux</tt>, our original 
    interest were computing list reversals, but then the
    auxiliary function computes a more general concept, namely, that
    of appending an auxiliary list to some list reversal.
    In the case of <tt>fast-factorial-aux</tt>, our original
    interest were computing factorials, but the auxiliary
    function computes a more general value, namely, the
    product of some auxiliary number with a factorial.
<li>At each level of recursion, the auxiliary function
    reduces the problem into a smaller subproblem, and 
    accumulating intermediate results in the accumulator
    variable.  In the case of <tt>list-reverse-aux</tt>, recursion
    is applied to the sublist <tt>(rest <em>L</em>)</tt>, while
    <tt>(first <em>L</em>)</tt> is <tt>cons</tt>'ed with <em>A</em>.
    In the case of <tt>fast-factorial</tt>, recursion is applied
    to <em>(N - 1)!</em>, while <em>N</em> is multiplied with <em>A</em>.
<li>The driver function initiates the recursion by providing
     an initial value for the auxiliary variable.
    In the case of computing 
    list reversals, <tt>list-reverse</tt> initializes
    <em>A</em> to <tt>nil</tt>.  In the case of computing factorials,
    <tt>fast-factorial</tt> initializes <em>A</em> to 1.
</ol>

<p>Now that you understand how <tt>fast-factorial</tt> works,
we explain where the adjective "fast" come from ...

<h2>Tail Recursions</h2>

Recursive functions are usually easier to reason about.  Notice 
how we articulate the correctness of recursive functions in this
and the previous tutorial.  However, some naive programmers
complain that recursive functions are slow when compared to
their iterative counter parts.  For example, consider the
original implementation of <tt>factorial</tt> we saw in the
previous tutorial:
<pre>
(defun factorial (N)
  "Compute the factorial of N."
  (if (= N 1)
      1
    (* N (factorial (- N 1)))))
</pre>
It is fair to point out that, as recursion unfolds, stack frames
will have to be set up, function arguments will have to be pushed
into the stack, so on and so forth, resulting in unnecessary
runtime overhead not experienced by the iterative counterpart
of the above <tt>factorial</tt> function:
<pre>
int factorial(int N) {
  int A = 1;
  while (N != 1) {
    A = A * N;
    N = N - 1;
  }
  return A;
}
</pre>
Because of this and other excuses, programmers conclude that
they could write off recursive implementations ...

<p>Modern compilers for functional programming languages usually
implement <em>tail-recursive call optimizations</em> which
automatically translate a certain kind of linear recursion into
efficient iterations.  A linear recursive function is <em>tail-recursive</em>
if the result of each recursive call is returned right away as the
value of the function.   Let's examine the implementation of 
<tt>fast-factorial</tt> again:
<pre>
(defun fast-factorial (N)
  "A tail-recursive version of factorial."
  (fast-factorial-aux N 1))

(defun fast-factorial-aux (N A)
  "Multiply A by the factorial of N."
  (if (= N 1)
      A
    (fast-factorial-aux (- N 1) (* N A))))
</pre>

<p>Notice that, in <tt>fast-factorial-aux</tt>, there is no work
left to be done after the recursive call <tt>(fast-factorial-aux
(- N 1) (* N A))</tt>.  Consequently, the compiler will not
create new stack frame or push arguments, but instead simply
bind <tt>(- N 1)</tt> to <tt>N</tt> and <tt>(* N A)</tt>
to <tt>A</tt>, and jump to the beginning of the function.
Such optimization effectively renders <tt>fast-factorial</tt>
as efficient as its iterative counterpart.  Notice also
the striking structural similarity between the two.

<p>When you implement linearly recursive functions, you are
encouraged to restructure it as a tail recursion after you
have fully debugged your implementation.  Doing so allows
the compiler to optimize away stack management code.
However, you should do so only after you get the prototype
function correctly implemented.  Notice that the technique
of accumulator variables can be used even when we are
not transforming code to tail recursions.  For some problems,
the use of accumulator variables offers the most natural solutions.

<p><hr><b>Exercise:</b>
Recall that the <em>N</em>'th <em>triangular number</em> is
defined to be <em>1 + 2 + 3 + ... + N</em>.
Give a tail-recursive implementation of the function
<tt>(fast-triangular <em>N</em>)</tt>
which returns the <em>N</em>'th triangular number.
<hr>

<p><hr><b>Exercise:</b>
Give a  tail-recursive implementation of the
function <tt>(fast-power <em>B</em> <em>E</em>)</tt> that
raises <em>B</em> to the power <em>E</em> (assuming that
both <em>B</em> and <em>E</em> are non-negative integers).
<hr>

<p><hr><b>Exercise:</b>
Give a tail-recursive implementation of the
function <tt>(fast-list-length <em>L</em>)</tt>, which
returns the length of a given list <em>L</em>.
<hr>

<h2>Functions as First-Class Objects</h2>

<p>A data type is <em>first-class</em> in a programming language when you
can pass instances of the data type as function arguments
or return them as function values.  We are used to treating
numeric and Boolean values as first-class data types in 
languages like Pascal and C.  However, we might not be familiar to the
notion
that functions could be treated as first-class objects, that is,
functions can be passed as function arguments and returned as
function values.  This unique feature of Common LISP and other
functional languages makes it easy to build very powerful abstractions.
In the remaining of this tutorial, we will look at what passing functional
arguments buys us.  In the fourth tutorial, when we talk about
imperative programming in LISP, we will return to the topic of
returning functional values.

<p>
Frequently, we need to apply a transformation multiple times on
the same data object.  For example, we could define the following
transformation:
<pre>
(defun double (x)
  "Multiple X by 2."
  (* 2 x))
</pre>
We could compute 2<sup>4</sup> 
by applying the <tt>double</tt> transformation
4 times on 1:
<pre>
USER(10): (double (double (double (double 1))))
16
</pre>
Not only is this clumsy, but it also fails to express the very idea
that the same transformation is applied multiple times.
It would be nice if we can repeat applying a given transformation <em>F</em>
 on <em>X</em> for <em>N</em> times by simply writing
<tt>(repeat-transformation <em>F</em> <em>N</em> <em>X</em>)</tt>.
The following function does just that:
<pre>
(defun repeat-transformation (F N X)
  "Repeat applying function F on object X for N times."
  (if (zerop N)
      X
    (repeat-transformation F (1- N) (funcall F X))))
</pre>
The definition follows the standard tail recursive pattern.  Notice
the form <tt>(funcall <em>F</em> <em>X</em>)</tt>.  Given 
a function <em>F</em> and objects <em>X<sub>1</sub></em>
<em>X<sub>2</sub></em> ... <em>X<sub>n</sub></em>,
the form <tt>(funcall <em>F</em> <em>X<sub>1</sub></em>
<em>X<sub>2</sub></em> ... <em>X<sub>n</sub></em>)</tt>
invoke the function <em>F</em> with arguments <em>X<sub>1</sub></em>,
<em>X<sub>2</sub></em>, ..., <em>X<sub>n</sub></em>.  The variable <em>N</em>
is a counter keeping track of the remaining number of times we need to apply
function <em>F</em> to the accumulator variable <em>X</em>.

<p>To pass a the function <tt>double</tt> as an argument to 
<tt>repeat-transformation</tt>, we need to annotate the function name
<tt>double</tt> by a <em>closure constructor</em>,
as in the following:
<pre>
USER(11): (repeat-transformation (function double) 4 1)
16
</pre>
There is nothing magical going on, the closure constructor is
just a syntax for telling Common LISP that what follows is a function
rather than a local variable name.  Had we not included the
annotation, Common LISP will treat the name <tt>double</tt> as a variable
name, and then report an error since the name <tt>double</tt> is not
defined.

<p>To see how the evaluation arrives at the result 16, we could,
as usual, trace the execution:
<pre>
USER(12): (trace repeat-transformation)
REPEAT-TRANSFORMATION
USER(13): (repeat-transformation #'double 4 1)
 0: (REPEAT-TRANSFORMATION #<Interpreted Function DOUBLE> 4 1)
   1: (REPEAT-TRANSFORMATION #<Interpreted Function DOUBLE> 3 2)
     2: (REPEAT-TRANSFORMATION #<Interpreted Function DOUBLE> 2 4)
       3: (REPEAT-TRANSFORMATION #<Interpreted Function DOUBLE> 1 8)
         4: (REPEAT-TRANSFORMATION #<Interpreted Function DOUBLE> 0 16)
         4: returned 16
       3: returned 16
     2: returned 16
   1: returned 16
 0: returned 16
16
</pre>

<h2>Higher-Order Functions</h2>

<p>Notice that exponentiation is not the only use of the 
<tt>repeat-transformation</tt> function.  Let's say we want to
build a list containing 10 occurrences of the symbol <tt>blah</tt>.
We can do so with the help of <tt>repeat-transformation</tt>:
<pre>
USER(30): (defun prepend-blah (L) (cons 'blah L))
PREPEND-BLAH
USER(31): (repeat-transformation (function prepend-blah) 10 nil)
(BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH)
</pre>

<p>Suppose we want to fetch the 7'th element of the list
<tt>(a b c d e f g h i j)</tt>.
  Of course, we could use the
built in function <tt>seventh</tt> to do the job, but for the fun of it, we
could also achieve what we want in the following way:
<pre>
USER(32): (first (repeat-transformation (function rest) 6 '(a b c d e f g h i j)))
G
</pre>
Basically, we apply <tt>rest</tt> six times before apply <tt>first</tt>
to get the seventh element.  In fact, we could have defined the function
<tt>list-nth</tt> (see previous tutorial) in the following way:
<pre>
(defun list-nth (N L)
  (first (repeat-transformation (function rest) N L)))
</pre>
(<tt>list-nth</tt> numbers the member of a list from zero onwards.)

<p>As you can see, functions that accepts other functions as arguments
are very powerful abstractions.  You can encapsulate generic
algorithms in such a function, and parameterize their behavior by
passing in different function arguments.  We call a function that
has functional parameters (or return a function as its value) 
a <em>higher-order</em> function.

<p>One last point before we move on.  The closure constructor <tt>function</tt>
is used very often when working with higher-order functions.  Common
LISP therefore provide another equivalent syntax to reduce typing.
When we want Common LISP to interpret a name <tt>F</tt>
as a function, instead
of typing <tt>(function F)</tt>, we can also type the shorthand
<tt>#'F</tt>.  The prefix <tt>#'</tt> is nothing but an alternative
syntax for the closure constructor.  For example, we could enter
the following:
<pre>
USER(33): (repeat-transformation #'double 4 1)
16
USER(34): (repeat-transformation #'prepend-blah 10 nil)
(BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH)
USER(35): (first (repeat-transformation #'rest 6 '(a b c d e f g h i j)))
G
</pre>

<h2>Lambda Expressions</h2>

<p>Some of the functions, like 
<tt>prepend-blah</tt> for example, serves no other purpose
but to instantiate the generic algorithm <tt>repeat-transformation</tt>.
It would be tedious if we need to define it as a global function
using <tt>defun</tt>
before we pass it into <tt>repeat-transformation</tt>.  Fortunately,
LISP provides a mechanism to help us define functions "in place":
<pre>
USER(36): (repeat-transformation #'(lambda (L) (cons 'blah L)) 10 nil)
(BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH)
</pre>
The first argument <tt>(lambda (L) (cons 'blah L))</tt> is a 
<em>lambda expression</em>.  It designates an anonymous function
(nameless function) with one parameter <tt>L</tt>, and it returns
as a function value <tt>(cons 'blah <em>L</em>)</tt>.  We prefix
the lambda expression with the closure constructor <tt>#'</tt>
since we want Common LISP to interpret the argument as a function
rather than a call to a function named <tt>lambda</tt>.

<p>Similarly, we could have computed powers as follows:
<pre>
USER(36): (repeat-transformation #'(lambda (x) (* 2 x)) 4 1)
16
</pre>

<p><hr><b>Exercise</b>:  Define a function <tt>(apply-func-list <em>L</em> 
<em>X</em>)</tt>
so that, given a list <em>L</em> of functions and an object <em>X</em>,
<tt>apply-func-list</tt> applies the functions in <em>L</em> to <em>X</em> in
reversed order.  For example, the following expression
<pre>
(apply-func-list (list #'double #'list-length #'rest) '(1 2 3))
</pre>
is equivalent to 
<pre>
(double (list-length (rest '(1 2 3))))
</pre>
<hr>

<p><hr><b>Exercise</b>: Use <tt>apply-func-list</tt> to compute the following:
<ol>
<li>10 times the fourth element of the list <tt>(10 20 30 40 50)</tt>,
<li>the third element of the second element in the list 
    <tt>((1 2) (3 4 5) (6))</tt>,
<li>the difference between 10 and the length of <tt>(a b c d e f)</tt>,
<li>a list containing a list containing the symbol <tt>blah</tt>.
</ol>
<hr>

<h2>Iterating Through a List</h2>

<p>We have seen how we could iterate through a list using linear 
recursion.  We have also seen how such recursion can be optimized
if structured in a tail-recursive form.  However, many of the
the list processing functions look striking similar.  Consider
the following examples:
<pre>
(defun double-list-elements (L)
  "Given a list L of numbers, return a list containing the elements of L multiplied by 2."
  (if (null L)
      nil
    (cons (double (first L)) (double-list-elements (rest L)))))

(defun reverse-list-elements (L)
  "Given a list L of lists, return a list containing the reversal of L's members."
  (if (null L)
      nil
    (cons (reverse (first L)) (reverse-list-elements (rest L)))))
</pre>
We could come up with infinitely many more examples of this sort.  
Having to write a new function everytime we want to iterate 
through a list is both time-consuming and error-prone.
The solution is to capture the generic logic of list iteration
in higher-order functions, and specialize their behaviors by
passing in functional arguments.

<p>If we look at the definitions of <tt>double-list-elements</tt>
and <tt>reverse-list-elements</tt>, we see that they 
apply a certain function to
the <tt>first</tt> element of their input, then recursively invoke
themselves to
process the <tt>rest</tt> of the input list,  and lastly
combine the result of the two function calls using <tt>cons</tt>.
  We could capture this
logic into the following function:
<pre>
(defun mapfirst (F L)
  "Apply function F to every element of list L, and return a list containing the results."
  (if (null L)
      nil
    (cons (funcall F (first L)) (mapfirst F (rest L)))))
</pre>

<p>The functions <tt>double-list-elements</tt>
and <tt>reverse-list-elements</tt> can be replaced by the following:
<pre>
USER(18): (mapfirst #'double '(1 2 3 4))
(2 4 6 8)
USER(19): (mapfirst #'reverse '((1 2 3) (a b c) (4 5 6) (d e f)))
((3 2 1) (C B A) (6 5 4) (F E D))
</pre>

<p>Of course, you could also pass lambda abstractions as arguments:
<pre>
USER(20): (mapfirst #'(lambda (x) (* x x)) '(1 2 3 4))
(1 4 9 16)
</pre>

<p>In fact, the higher-order function is so useful that
Common LISP defines a function <tt>mapcar</tt> that does
exactly what <tt>mapfirst</tt> is intended for:
<pre>
USER(22): (mapcar #'butlast '((1 2 3) (a b c) (4 5 6) (d e f)))
((1 2) (A B) (4 5) (D E))
</pre>
The reason why it is called <tt>mapcar</tt> is that the function
<tt>first</tt> was called <tt>car</tt> in some older dialects of
LISP (and <tt>rest</tt> was called <tt>cdr</tt> in those dialects;
Common LISP still supports <tt>car</tt> and <tt>cdr</tt> but
we strongly advice you to stick with the more readable <tt>first</tt>
and <tt>rest</tt>).  We suggest you to consider using <tt>mapcar</tt>
whenever you are tempted to write your own list-iterating functions.

<p>The function <tt>mapcar</tt> is an example of <em>generic iterators</em>,
which capture the generic logic of iterating through a list.
If we look at what we do the most when we iterate through a list,
we find that the following kinds of iterations occurs most frequently
in our LISP programs:
<ol>
<li><em>Transformation iteration</em>: transforming a list by
     systematically applying a monadic function to the elements
     of the list.
<li><em>Search iteration</em>: searching for a list member that
      satisfies a given condition.
<li><em>Filter iteration</em>: screening out all members that
      does not satisfy a given condition.
</ol>
As we have already seen, <tt>mapcar</tt> implements the generic
algorithm for performing transformation iteration.  In the following,
we will look at the analogous of <tt>mapcar</tt> for the
remaining iteration categories.

<h2>Search Iteration</h2>

<p>Let us begin by writing a function that returns an even element in
a list of numbers:
<pre>
(defun find-even (L)
  "Given a list L of numbers, return the leftmost even member."
  (if (null L)
      nil
    (if (evenp (first L))
        (first L)
      (find-even (rest L)))))
</pre>

<p><hr><b>Exercise:</b> Implement a function that, when given a list <em>L</em>
   of lists, return a non-empty member of <em>L</em>.
<hr>

<p>We notice that the essential logic of searching can be extracted out
into the following definition:
<pre>
(defun list-find-if (P L)
  "Find the leftmost element of list L that satisfies predicate P."
  (if (null L)
      nil
    (if (funcall P (first L))
        (first L)
      (list-find-if P (rest L)))))
</pre>
The function <tt>list-find-if</tt> examines the elements of <em>L</em>
one by one, and return the first one that satisfies predicate <em>P</em>.
The function can be used for locating even or non-<tt>nil</tt> members
in a list:
<pre>
USER(34): (list-find-if #'evenp '(1 3 5 8 11 12))
8
USER(35): (list-find-if #'(lambda (X) (not (null X))) '(nil nil (1 2 3) (4 5)))
(1 2 3)
</pre>

<p>Common LISP defines a built-in function <tt>find-if</tt> which is
a more general version of <tt>list-find-if</tt>.  It can be used just
like <tt>list-find-if</tt>:
<pre>
USER(37): (find-if #'evenp '(1 3 5 8 11 12))
8
USER(38): (find-if #'(lambda (X) (not (null X))) '(nil nil (1 2 3) (4 5)))
(1 2 3)
</pre>

<p><hr><b>Exercise</b>: Use <tt>find-if</tt> to define 
a function that
searches among a list of lists for a member 
that has length at least 3.
<hr>
<p><hr><b>Exercise</b>: Use <tt>find-if</tt> to define
a function that searches among a list of lists for a member that
contains an even number of elements.
<hr>
<p><hr><b>Exercise</b>: Use <tt>find-if</tt> to define
a function that searches among a list of numbers for 
a member that is divisible by three.
<hr>

<h2>Filter Iteration</h2>

<p>Given a list of lists, suppose we want to screen out all the 
member lists with length less than three.  We could do so by 
the following function:
<pre>
(defun remove-short-lists (L)
  "Remove all members of L that has length less than three."
  (if (null L)
      nil
    (if (< (list-length (first L)) 3)
        (remove-short-lists (rest L))
      (cons (first L) (remove-short-lists (rest L))))))
</pre>
To articulate the correctness of this implementation, consider the
following.  The list <em>L</em> is either <tt>nil</tt> or constructed
by <tt>cons</tt>.
<ul>
<li><em>Case 1</em>: <em>L</em> is <tt>nil</tt>.<br>
    Removing short lists from an empty list simply results in
    an empty list.
<li><em>Case 2</em>: <em>L</em> is constructed by <tt>cons</tt>.<br>
    <em>L</em> has two components: <tt>(first <em>L</em>)</tt> and
    <tt>(rest <em>L</em>)</tt>.  We have two cases: either <tt>(first 
    <em>L</em>)</tt> has fewer than 3 members or it has at least 3 members.
    <ul>
    <li><em>Case 2.1</em>: <tt>(first <em>L</em>)</tt>
       has fewer than three elements.<br>
      Since <tt>(first <em>L</em>)</tt> is short, and will not appear
      in the result of removing short lists from <em>L</em>, the latter
      is equivalent to the result of removing short lists from
      <tt>(rest <em>L</em>)</tt>.
    <li><em>Case 2.2</em>: <tt>(first <em>L</em>)</tt>
      has at least three elements.<br>
      Since <tt>(first <em>L</em>)</tt> is not short, and will appear
      in the result of removing short lists from <em>L</em>, the latter
      is equivalent to adding <tt>(first <em>L</em>)</tt> to the
      result of removing short lists from <tt>(rest <em>L</em>)</tt>.
    </ul>
</ul>
A typical execution trace is the following:
<pre>
USER(17): (remove-short-lists '((1 2 3) (1 2) nil (1 2 3 4)))
 0: (REMOVE-SHORT-LISTS ((1 2 3) (1 2) NIL (1 2 3 4)))
   1: (REMOVE-SHORT-LISTS ((1 2) NIL (1 2 3 4)))
     2: (REMOVE-SHORT-LISTS (NIL (1 2 3 4)))
       3: (REMOVE-SHORT-LISTS ((1 2 3 4)))
         4: (REMOVE-SHORT-LISTS NIL)
         4: returned NIL
       3: returned ((1 2 3 4))
     2: returned ((1 2 3 4))
   1: returned ((1 2 3 4))
 0: returned ((1 2 3) (1 2 3 4))
((1 2 3) (1 2 3 4))
</pre>

<p>Alternatively, we could have removed short lists using Common LISP's
built-in function <tt>remove-if</tt>:
<pre>
USER(19): (remove-if #'(lambda (X) (< (list-length X) 3)) '((1 2 3) (1 2) nil (1 2 3 4)))
((1 2 3) (1 2 3 4))
</pre>

<p>The function <tt>(remove-if <em>P</em> <em>L</em>)</tt> constructs
a new version of list <em>L</em> that contains only members not satisfying
predicate <em>P</em>.  For example, we can remove all 
even members from the list <tt>(3 6 8 9 10 13 15 18)</tt> by the
following:
<pre>
USER(21): (remove-if #'(lambda (X) (zerop (rem x 2))) '(3 6 8 9 10 13 15 18))
(3 9 13 15)
</pre>
Without <tt>remove-if</tt>, we would end up having to implement a function
like the following:
<pre>
(defun remove-even (L)
  "Remove all members of L that is an even number."
  (if (null L)
      nil
    (if (zerop (rem (first L) 2))
        (remove-even (rest L))
      (cons (first L) (remove-even (rest L))))))
</pre>

<p><hr><b>Exercise</b>: Demonstrate the correctness of  <tt>remove-even</tt>
   using arguments you have seen in this tutorial.
<hr>
<p><hr><b>Exercise</b>: Observe the recurring pattern in 
  <tt>remove-short-lists</tt>
 and <tt>remove-even</tt>, and implement your own version of
<tt>remove-if</tt>.
<hr>
<p>We could actually implement <tt>list-intersection</tt> using
<tt>remove-if</tt> and lambda abstraction:
<pre>
(defun list-intersection (L1 L2)
  "Compute the intersection of lists L1 and L2."
  (remove-if #'(lambda (X) (not (member X L2))) L1))
</pre>
In the definition above, the lambda abstraction evaluates to a 
predicate that returns true if its argument is not a member of 
<em>L2</em>.  Therefore, the <tt>remove-if</tt> expression
removes all elements of <em>L1</em> that is not a member of <em>L2</em>.
This precisely gives us the intersection of <em>L1</em> and <em>L2</em>.

<p><hr><b>Exercise</b>: Use <tt>remove-if</tt> and lambda abstractions
     to implement <tt>list-difference</tt>.
<hr>
<p><hr><b>Exercise</b>: Look up the functionality of <tt>remove-if-not</tt>
   in CTRL2.  Re-implement <tt>list-intersection</tt> using 
<tt>remove-if-not</tt> and lambda abstraction.
<hr>

<h2>Functions Returning Multiple Values</h2>

<p>The functions we have seen so far return a single value, but some
LISP functions return two or more values.  For example, if two arguments
<em>number</em> and <em>divisor</em> are passed to the <tt>floor</tt>
function, it returns two values, the quotient <em>q</em> and the
remainder <em>r</em> so that <em>number = divisor * q + r</em>.
<pre>
USER(11): (floor 17 5)
3
2
USER(12): (floor -17 5)
-4
3
</pre>
Regular binding constructs like <tt>let</tt> and <tt>let*</tt>
only allows us to catch the first returned value of a multiple-valued
function, as the following example illustrates:
<pre>
USER(13): (let ((x (floor 17 5))) x)
3
</pre>
One can use the <tt>multiple-value-bind</tt> to receive the results of 
a multiple-valued function:
<pre>
USER(14): (multiple-value-bind (x y) (floor 17 5) 
            (+ x y))
5
</pre>
In the above expression, <tt>(x y)</tt> is the list of variables
binding to the returned values, <tt>(floor 17 5)</tt> is the
expression generating multiple results.  Binding the two values
of <tt>(floor 17 5)</tt> to <tt>x</tt> and <tt> y</tt>, LISP
then evaluates the expression <tt>(+ x y)</tt>.

<p>One may also write LISP functions that return multiple values:
<pre>
(defun order (a b)
  "Return two values: (min a b) and (max a b)."
  (if (>= a b)
      (values b a)
    (values a b)))
</pre>
The <tt>values</tt> special form returns its arguments as multiple
values.

<p>For more information about LISP constructs for handling
multiple values, consult section 7.10 of CLTL2.

<p><hr><b>Exercise:</b> Implement a tail-recursive 
function <tt>(list-min-max
<em>L</em>)</tt> that returns two values: the minimum
and maximum members of a list <em>L</em> of numbers.
<hr>

</body>
</html>