-
Notifications
You must be signed in to change notification settings - Fork 10
/
series.tex
1822 lines (1577 loc) · 81.4 KB
/
series.tex
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
%%%Chapter of Common Lisp Manual. Copyright 1989 Guy L. Steele Jr.
% +++ Final version of chapter +++
\clearpage\def\pagestatus{FINAL PROOF}
\chapter{Series}
\label{SERIES}
\def\SU#1{${}_{#1}$}
\def\fooprime#1{#1'}
Author: Richard C. Waters
\begin{new}
\prefaceword A series is a data structure much like a sequence, with similar
kinds of operations. The difference is that in many situations, operations
on series may be composed functionally and yet execute iteratively, without
the need to construct intermediate series values explicitly. In this
manner, series provide both the clarity of a functional programming style
and the efficiency of an iterative programming style.
The remainder of this chapter consists of a description by Richard
C.~Waters of his work on an existing implementation of series.
This is the culmination of many years of design and use of this approach,
during which some 100,000 lines of application code have been written (by
about half a dozen people over the course of seven years) using the series
facility in nearly all iteration situations. This includes one large
system (\cdf{KBEmacs}) of over 40,000 lines of code.
I have edited the chapter only very lightly to conform to the overall style
of this book. Please see the Preface to this book for more information
about the genesis of the series approach and its relationship to the work
of X3J13.
\end{new}
\noindent\hbox to \textwidth{\hss---Guy L. Steele Jr.}
\vskip 8pt plus 3pt minus 2pt
\section{Introduction}
Series combine aspects of sequences, streams, and loops. Like sequences,
series represent totally ordered multi-sets. In addition, the series
functions have the same flavor as the sequence functions---namely, they
operate on whole series, rather than extracting elements to be
processed by other functions. For instance, the series expression below
computes the sum of the positive elements in a list.
\begin{lisp}
(collect-sum (choose-if \#'plusp (scan '(1 -2 3 -4)))) {\EV} 4
\end{lisp}
Like streams, series can represent unbounded sets of elements and are
supported by lazy evaluation: each element of a series is not
computed until it is needed. For instance, the series expression below
returns a list of the first five even natural numbers and their sum. The
call on \cdf{scan-range} returns a series of all the even natural numbers.
However, since no elements beyond the first five are ever used, no elements
beyond the first five are ever computed.
\begin{lisp}
(let ((x (subseries (scan-range :from 0 :by 2) 0 5))) \\*
~~(values (collect x) (collect-sum x))) \\*
~~{\EV} (0 2 4 6 8) {\rm and} 20
\end{lisp}
Like sequences and unlike streams, a series is not altered
when its elements are accessed. For instance, both users of \cdf{x}
above receive the same elements.
A totally ordered multi-set of elements can be represented in a loop by the
successive values of a variable. This is extremely efficient, because it
avoids the need to store the elements as a group in any kind of data
structure. In most situations, series expressions achieve this same high
level of efficiency, because they are automatically transformed into loops
before being evaluated or compiled. For instance, the first expression
above is transformed into a loop like the following.
\begin{lisp}
(let ((sum 0)) \\*
~~(dolist (i '(1 -2 3 -4) sum) \\*
~~~~(when (plusp i) (setq sum (+ sum i))))) {\EV} 4
\end{lisp}
A wide variety of algorithms can be expressed clearly and succinctly with
series expressions. In particular, at least 90 percent of the loops
programmers typically write can be replaced by series expressions that are
much easier to understand and modify, and just as efficient. From this
perspective, the key feature of series is that they are supported by a rich
set of functions. These functions more or less correspond to the union of
the operations provided by the sequence functions, the \cdf{loop} clauses,
and the vector operations of APL.
Some series expressions cannot be transformed into loops.
This is unfortunate, because while transformable series expressions are much more
efficient than equivalent expressions involving sequences or streams,
non-transformable series expressions are much less efficient. Whenever a
problem comes up that blocks the transformation of a series expression, a
warning message is issued. On the basis of information in the message, it is
usually easy to provide an efficient fix for the problem (see
section~\ref{SERIES-E-SECTION}).
Fortunately, most series expressions can be transformed into loops. In
particular, pure expressions (ones that do not store series in variables)
can always be transformed. As a result, the best approach for programmers
to take is simply to write series expressions without worrying about
transformability. When problems come up, they can be ignored (since they
cannot lead to the computation of incorrect results) or dealt with on an
individual basis.
\beforenoterule
\begin{implementation}
The series functions and the theory
underlying them are described in greater detail
in~\cite{WATERS-SERIES-DESIGN,WATERS-SERIES-IMPLEMENTATION}.
These reports also discuss the algorithms required to transform series
expressions into loops and explain how to obtain a portable implementation.
\end{implementation}
\afternoterule
\section{Series Functions}
\label{SERIES-F-SECTION}
Throughout this chapter the notation \cd{S\SU{j}} is used to
denote the \emph{j\/}th element of the series \cdf{S}. As in a list or
vector, the first element of a series has the subscript zero.
The \cd{\#} macro character syntax \cd{\#Z\emph{list}} denotes a series that contains
the elements of \emph{list}. This syntax is also used when series are printed.
\begin{lisp}
(choose-if \#'symbolp \#Z(a 2 b)) {\EV} \#Z(a b)
\end{lisp}
Series are self-evaluating objects and the series data type is disjoint
from all other types.
\begin{defun}[Type specifier]
series element-type
The type specifier \cd{(series \emph{element-type})}
denotes the set of series whose elements are all
members of the type \emph{element-type}.
\end{defun}
\begin{defun}[Function]
series arg &rest args
The function \cdf{series} returns an unbounded series that endlessly repeats the
values of the arguments. The second example below shows the preferred
method for constructing a bounded series.
\begin{lisp}
(series 'b 'c) {\EV} \#Z(b c b c b c ...) \\
(scan (list 'a 'b 'c)) {\EV} \#Z(a b c)
\end{lisp}
\end{defun}
\subsection{Scanners}
Scanners create series outputs based on non-series inputs. Either they
operate based on some formula (for example, scanning a range of integers) or they
enumerate the elements in an aggregate data structure (for example, scanning the
elements in a list or array).
\begin{defun}[Function]
scan-range &key (:start 0) (:by 1) (:type 'number)
:upto :below :downto :above :length
The function \cdf{scan-range} returns a series of numbers starting with the
\cd{:start} argument
(default integer \cd{0}) and counting up by the \cd{:by} argument (default
integer \cd{1}). The \cd{:type} argument (default \cdf{number}) is
a type specifier indicating the type of numbers in the series
produced. The \cd{:type} argument must be a (not necessarily proper) subtype of
\cdf{number}. The \cd{:start} and \cd{:by} arguments must be of that type.
One of the last five arguments may be used
to specify the kind of end test to be used;
these are called \emph{termination arguments}.
If \cd{:upto} is specified, counting continues only so long as the
numbers generated are less than or equal to \cd{:upto}. If
\cd{:below} is specified, counting continues only so long as the numbers
generated are less than \cd{:below}. If \cd{:downto} is specified,
counting continues only so long as the numbers generated are greater
than or equal to \cd{:downto}. If \cd{:above} is specified,
counting continues only so long as the numbers generated are greater
than \cd{:above}. If \cd{:length} is specified, it must be a
non-negative integer and the output series has this length.
If none
of the termination arguments are specified, the output has unbounded
length. If more than one termination argument is specified, it is an error.
\begin{lisp}
(scan-range :upto 4) {\EV} \#Z(0 1 2 3 4) \\*
(scan-range :from 1 :by -1 :above -4) {\EV} \#Z(1 0 -1 -2 -3) \\
(scan-range :from .5 :by .1 :type 'float) {\EV} \#Z(.5 .6 .7 ...) \\*
(scan-range) {\EV} \#Z(0 1 2 3 4 5 6 ...)
\end{lisp}
\end{defun}
\begin{defun}[Function]
scan sequence \\
scan type sequence
\cdf{scan} returns a series containing the elements of \emph{sequence} in
order. The \emph{type} argument is a type specifier indicating the type of
sequence to be scanned; it must be a (not necessarily proper) subtype of
\cdf{sequence}. If \emph{type} is omitted, it defaults to \cdf{list}.
(This function exhibits an argument pattern that is unusual for Common
Lisp: an ``optional'' argument preceding a required argument. This
pattern cannot be expressed in the usual manner with \cd{\&optional}. It
is indicated above by two definition lines, showing the two possible
argument patterns.)
If the \emph{sequence} is a list, it must be a proper list ending in \cdf{nil}.
Scanning is significantly more efficient if it can be determined at compile
time whether \emph{type} is a subtype of \cdf{list} or \cdf{vector} and for
vectors what the length of the vector is.
\begin{lisp}
(scan '(a b c)) {\EV} \#Z(a b c) \\*
(scan 'string "BAR") {\EV} \#Z(\#{\Xbackslash}B \#{\Xbackslash}A \#{\Xbackslash}R)
\end{lisp}
\end{defun}
\begin{defun}[Function]
scan-sublists list
\cdf{scan-sublists} returns a series containing the successive sublists of
\emph{list}. The \emph{list} must be a proper list ending in \cdf{nil}.
\begin{lisp}
(scan-sublists '(a b c)) {\EV} \#Z((a b c) (b c) (c))
\end{lisp}
\end{defun}
\begin{defun}[Function]
scan-multiple type first-sequence &rest more-sequences
Several sequences can be scanned at once by using several calls on
\cdf{scan}. Each call on \cdf{scan} will test to see when its sequence runs
out of elements and execution will stop as soon as any of the sequences are
exhausted. Although very robust, this approach to scanning can be
inefficient. In situations where it is known in
advance which sequence is the shortest, \cdf{scan-multiple} can be used to
obtain the same results more rapidly.
\cdf{scan-multiple} is similar to \cdf{scan} except that several sequences
can be scanned at once. If there are \emph{n} sequence inputs,
\cdf{scan-multiple} returns \emph{n} series containing the elements of these
sequences. It must be the case that none of the sequence inputs is shorter
than the first sequence. All of the output series are the same length as
the first input sequence. Extra elements in the other input sequences are
ignored. Using \cdf{scan-multiple} is more efficient than using multiple
instances of \cdf{scan}, because \cdf{scan-multiple} only has to check for
the first input running out of elements.
If \emph{type} is of the form \cd{(values~$\emph{t}_1$~$\ldots$~$\emph{t}x_m$)}, then
there must be $\emph{m}$ sequence inputs and the \emph{i\/}th sequence must have type
$\emph{t}_{i}$. Otherwise there can be any number of sequence inputs, each of which
must have type \emph{type}.
\begin{lisp}
(multiple-value-bind (data weights) \\*
~~~~(scan-multiple 'list '(1 6 3 2 8) '(2 3 3 3 2)) \\*
~~(collect (map-fn t \#'* data weights))) \\*
~~{\EV} (2 18 9 6 16)
\end{lisp}
\end{defun}
\begin{defun}[Function]
scan-lists-of-lists lists-of-lists &optional leaf-test \\
scan-lists-of-lists-fringe lists-of-lists &optional leaf-test
The argument \emph{lists-of-lists} is viewed as a tree where each
internal node is a non-empty list and the elements of the list are the
children of the node. \cdf{scan-lists-of-lists} and
\cdf{scan-lists-of-lists-fringe} each scan \emph{lists-of-lists} in preorder
and return a series of its nodes. \cdf{scan-lists-of-lists} returns every
node in the tree. \cdf{scan-lists-of-lists-fringe} returns only the leaf
nodes.
The scan proceeds as follows. The argument \emph{lists-of-lists} can be any
Lisp object. If \emph{lists-of-lists} is an atom or satisfies the predicate
\emph{leaf-test} (if present), it is a leaf node. (The predicate can count
on being applied only to conses.) Otherwise, \emph{lists-of-lists} is a (not
necessarily proper) list. The first element of \emph{lists-of-lists} is
recursively scanned in full, followed by the second and so on until a
non-cons \emph{cdr} is encountered. Whether or not this final \emph{cdr} is
\cdf{nil}, it is ignored.
\begin{lisp}
(scan-lists-of-lists '((2) (nil))) \\*
~~{\EV} \#Z(((2) (nil)) (2) 2 (nil) nil) \\*
(scan-lists-of-lists-fringe '((2) (nil))) {\EV} \#Z(2 nil) \\*
(scan-lists-of-lists-fringe '((2) (nil)) \\*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~\#'(lambda (e) (numberp (car e)))) \\*
~~{\EV} \#Z((2) nil)
\end{lisp}
\end{defun}
\begin{defun}[Function]
scan-alist a-list &optional (test \#'eql) \\
scan-plist plist \\
scan-hash table
When given an association list, a property list, or a hash table
(respectively), each of these functions produces two outputs: a series of keys
\emph{K} and a series of the corresponding values \emph{V}. Each key in the
input appears exactly once in the output, even if it appears more than once
in the input. (The \emph{test} argument of \cdf{scan-alist} specifies the
equality test between keys; it defaults to \cdf{eql}.)
The two outputs have the same length. Each
\emph{V}\SU{j} is the value returned by the appropriate accessing function
(\cdf{cdr} of \cdf{assoc}, \cdf{getf}, or \cdf{gethash}, respectively)
when given \emph{K}\SU{j}. \cdf{scan-alist} and \cdf{scan-plist} scan keys
in the order
they appear in the underlying structure. \cdf{scan-hash} scans keys in no
particular order.
\begin{lisp}
(scan-plist '(a 1 b 3)) {\EV} \#Z(a b) {\rm and} \#Z(1 3) \\*
(scan-alist '((a . 1) nil (a . 3) (b . 2))) \\*
~~{\EV} \#Z(a b) {\rm and} \#Z(1 2)
\end{lisp}
\end{defun}
\begin{defun}[Function]
scan-symbols &optional (package *package*)
\cdf{scan-symbols} returns a series, in no particular order, and possibly
containing duplicates, of the symbols accessible in \emph{package} (which
defaults to the current package).
\end{defun}
\begin{defun}[Function]
scan-file file-name &optional (reader \#'read)
\cdf{scan-file} opens the file named by the string \emph{file-name}
and applies the function \emph{reader} to it repeatedly until the end of the
file is reached. \emph{Reader} must accept the standard input function
arguments \emph{input-stream}, \emph{eof-error-p}, and \emph{eof-value} as its
arguments. (For instance, \emph{reader} can be \cdf{read},
\cdf{read-preserving-white-space}, \cdf{read-line}, or
\cdf{read-char}.) If omitted, \emph{reader} defaults to \cdf{read}.
\cdf{scan-file} returns a series of the values returned
by \emph{reader}, up to but not including the value returned
when the end of the file is reached. The
file is correctly closed, even if an abort occurs. \end{defun}
\begin{defun}[Function]
scan-fn type init step &optional test
The higher-order function \cdf{scan-fn} supports the general concept of
scanning. The \emph{type} argument is a type specifier indicating
the type of values returned by \emph{init} and \emph{step}. The \cdf{values}
type specifier can be used for this argument
to indicate multiple types; however, \emph{type} cannot
indicate zero values. If \emph{type} indicates $\emph{m}$ types
$\emph{t}_1, \ldots\,, \emph{t}_{m}$,
then \cdf{scan-fn} returns $\emph{m}$ series
\emph{T1}, $\ldots\,$, \emph{Tm}, where \emph{Ti} has
the type \cd{(series $\emph{t}_{i}$)}.
The arguments \emph{init}, \emph{step}, and \emph{test} are functions.
The \emph{init} must be of type
\cd{(function () (values $\emph{t}_1$ ... $\emph{t}_{m}$))}.
The \emph{step} must be of type
\cd{(function ($\emph{t}_1$ ... $\emph{t}_{m}$) (values $\emph{t}_1$ ... $\emph{t}_{m}$))}.
The \emph{test} (if present) must be of type
\cd{(function ($\emph{t}_1$ ... $\emph{t}_{m}$) t)}.
The elements of the \emph{Ti} are computed as follows:
\begin{lisp}
(values \emph{T1}\SU{0} ... \emph{Tm}\SU{0}) = (funcall \emph{init}) \\*
(values \emph{T1}\SU{j} ... \emph{Tm}\SU{j}) = (funcall \emph{step} \emph{T1}\SU{(j-1)} ... \emph{Tm}\SU{(j-1)})
\end{lisp}
The outputs all have the same length. If there is no \emph{test}, the
outputs have unbounded length. If there is a \emph{test}, the outputs
consist of the elements up to, but not including, the first elements (with
index \emph{j}, say) for which the following termination test is not \cdf{nil}.
\begin{lisp}
(funcall \emph{test} \emph{T1}\SU{j} ... \emph{Tm}\SU{j})
\end{lisp}
It is guaranteed that \emph{step} will
not be applied to the elements that pass this termination test.
If \emph{init}, \emph{step}, or \emph{test} has side effects when
invoked, it can count on being called in the order indicated by the
equations above, with \emph{test} called just before \emph{step} on each
cycle. However, given the lazy evaluation nature of series, these
functions will not be called until their outputs are actually used (if
ever). In addition, no assumptions can be made about the relative order of
evaluation of these calls with regard to execution in other parts of a
given series expression. The first example below scans down a list
stepping two elements at a time. The second example generates two unbounded
series: the integers counting up from 1 and the sequence of partial
sums of the first \emph{i} integers.
\begin{lisp}
(scan-fn t \#'(lambda () '(a b c d)) \#'cddr \#'null) \\*
~~{\EV} \#Z((a b c d) (c d)) \\
\\
(scan-fn '(values integer integer) \\*
~~~~~~~~~\#'(lambda () (values 1 0)) \\*
~~~~~~~~~\#'(lambda (i sum) (values (+ i 1) (+ sum i)))) \\*
~~{\EV} \#Z(1 2 3 4 ...) {\rm and} \#Z(0 1 3 6 ...)
\end{lisp}
\end{defun}
\begin{defun}[Function]
scan-fn-inclusive type init step test
The higher-order function \cdf{scan-fn-inclusive} is the same as
\cdf{scan-fn} except that the first set of elements for which \emph{test}
returns a non-null value is included in the output. As with
\cdf{scan-fn}, it is guaranteed that \emph{step} will not be applied to the
elements for which \emph{test} is non-null.
\end{defun}
\subsection{Mapping}
By far the most common kind of series operation is mapping. In cognizance
of this fact, four different ways are provided for specifying mapping: one
fundamental form (\cdf{map-fn}) and three shorthand forms that are more
convenient in particular common situations.
\begin{defun}[Function]
map-fn type function &rest series-inputs
The higher-order function \cdf{map-fn} supports the general concept of
mapping. The \emph{type} argument is a type specifier indicating
the type of values returned by \emph{function}. The \cdf{values}
construct can be used to indicate multiple types; however, \emph{type}
cannot indicate zero values. If \emph{type} indicates $m$ types
$t_1, \ldots\,, t_m$,
then \cdf{map-fn} returns $m$ series
\emph{T1},~$\ldots\,$,~\emph{Tm}, where \emph{Ti} has the
type \cd{(series~$t_i$)}.
The argument
\emph{function} is a function. The remaining arguments (if any) are all
series. Let these series be \emph{S1},~$\ldots\,$,~\emph{Sn} and suppose that
\emph{Si} has the type \cd{(series~$\emph{s}_{i}$)}.
The \emph{function} must be of type
\begin{lisp}
(function ($\emph{s}_1$ ... $\emph{s}_{n}$) (values $\emph{t}_1$ ... $\emph{t}_{m}$))
\end{lisp}
The length of each output is the same as the length of the shortest input.
If there are no bounded series inputs, the outputs are unbounded.
The elements of the \emph{Ti} are the results of applying \emph{function} to
the corresponding elements of the series inputs.
\begin{lisp}
(values \emph{T1}\SU{j} ... \emph{Tm}\SU{j}) {\EQ} (funcall \emph{function} \emph{S1}\SU{j} ... \emph{Sn}\SU{j})
\end{lisp}
If \emph{function} has side effects, it can count on being called first on
the \emph{Si}\SU{0}, then on the \emph{Si}\SU{1}, and so on. However, given
the lazy evaluation nature of series, \emph{function} will not be called on
any group of input elements until the result is actually used (if ever).
In addition, no assumptions can be made about the relative order of
evaluation of the calls on \emph{function} with regard to execution in other parts of a
given series expression.
\begin{lisp}
(map-fn 'integer \#'+ \#Z(1 2 3) \#Z(4 5)) {\EV} \#Z(5 7) \\*
(map-fn t \#'gensym) {\EV} \#Z(\#:G3 \#:G4 \#:G5 ...) \\
(map-fn '(values integer rational) \#'floor \#Z(1/4 9/5 12/3)) \\*
~~{\EV} \#Z(0 1 4) {\rm and} \#Z(1/4 4/5 0)
\end{lisp}
The \cd{\#} macro character syntax \cd{\#M} makes it easy to specify uses of \cdf{map-fn}
where \emph{type} is \cdf{t} and the \emph{function} is a named
function. The notation \cd{(\#M\emph{function}~...)} is an
abbreviation for \cd{(map-fn~t~\#'\emph{function}~...)}. The form \emph{function} can
be the printed representation of any Lisp object. The notation
\cd{\#M}\emph{function} can appear only in the
function position of a list.
\begin{lisp}
(collect (\#M1+ (scan '(1 2 3)))) {\EV} (2 3 4)
\end{lisp}
\end{defun}
\begin{defmac}
mapping ({({var | ({var}*)} value)}*) {declaration}* {form}*
The macro \cdf{mapping} makes it easy to specify uses of \cdf{map-fn}
where \emph{type} is \cdf{t} and the \emph{function} is a literal
\cdf{lambda}. The syntax of \cdf{mapping} is analogous to that of \cdf{let}.
The binding list specifies zero or more variables that are bound in parallel to
successive values of series. The \emph{value} part of each pair is
an expression that must produce a
series. The \emph{declarations} and \emph{forms} are
treated as the body of a \cdf{lambda} expression
that is mapped over the series values. A series of the first values
returned by this \cdf{lambda} expression is returned as the result of
\cdf{mapping}.
\begin{lisp}
(mapping ((x r) (y s)) ...) {\EQ} \\*
~~(map-fn t \#'(lambda (x y) ...) r s) \\
\\
(mapping ((x (scan '(2 -2 3)))) \\*
~~(expt (abs x) 3)) \\*
~~{\EV} \#Z(8 8 27)
\end{lisp}
The form \cdf{mapping} supports a special syntax that facilitates the
use of series functions returning multiple values. Instead of being
a single variable, the variable part of a \emph{var-value} pair can be a list of
variables. This list is treated the same way as the first argument to
\cdf{multiple-value-bind} and can be used to access the elements of
multiple series returned by a series function.
\begin{lisp}
(mapping (((i v) (scan-plist '(a 1 b 2)))) \\*
~~(list i v)) \\*
~~{\EV} \#Z((a 1) (b 2))
\end{lisp}
\end{defmac}
\begin{defmac}
iterate ({({var | ({var}*)} value)}*) {declaration}* {form}*
The form \cdf{iterate} is the same as \cdf{mapping}, except that after
mapping the \emph{forms} over the \emph{values}, the results are discarded and
\cdf{nil} is returned.
\begin{lisp}
(let ((item (scan '((1) (-2) (3))))) \\*
~~(iterate ((x (\#Mcar item))) \\*
~~~~(if (plusp x) (prin1 x)))) \\*
~~{\EV} nil {\rm (after printing ``\cd{13}'')}
\end{lisp}
To a first approximation, \cdf{iterate} and \cdf{mapping} differ in the same
way as \cdf{mapc} and \cdf{mapcar}. In particular, like \cdf{mapc},
\cdf{iterate} is intended to be used in situations where the \emph{forms} are
being evaluated for side effects rather than for their results. However, given
the lazy evaluation semantics of series, the difference between
\cdf{iterate} and \cdf{mapping} is more than just a question of efficiency.
If \cdf{mapcar} is used in a situation where the output is not used, time is
wasted unnecessarily creating the output list. However, if \cdf{mapping} is
used in a situation where the output is not used, no computation is
performed, because series elements are not computed until they are used.
Thus \cdf{iterate} can be thought of as a declaration that the indicated
computation is to be performed even though the output is not used for
anything.
\end{defmac}
\subsection{Truncation and Other Simple Transducers}
Transducers compute series from series and form the heart of most series
expressions. Mapping is by far the most common transducer. This section
presents a number of additional simple transducers.
\begin{defun}[Function]
cotruncate &rest series-inputs \\
until bools &rest series-inputs \\
until-if pred &rest series-inputs
Each of these functions accepts one or more series inputs {\it
S1},~$\ldots\,$,~\emph{Sn} as its \cd{\&rest} argument and returns $\emph{n}$ series
outputs \emph{T1},~$\ldots\,$,~\emph{Tn} that contain the same elements in the same
order---that is, \emph{Ti\SU{j}=Si\SU{j}}.
Let $\emph{k}$ be the length of the
shortest input \emph{Si}. \cdf{cotruncate} truncates the series so that
each output has length $\emph{k}$. Let $\emph{k}'$ be the position of the first element
in the boolean series \emph{bools} that is not \cdf{nil} or, if every
element is \cdf{nil}, the length of \emph{bools}. \cdf{until} truncates the
series so that each output has length \cd{(min~\emph{k}~$\fooprime{\emph{k}}$)}.
Let ${it k}''$ be the position of the first element in \emph{S1} such that
\cd{(\emph{pred}~\emph{S1\SU{\fooprime{\fooprime{k}}}})}
is not \cdf{nil} or, if there is no such
element, the length of \emph{S1}. \cdf{until-if} truncates the series so
that each output has length \cd{(min~\emph{k}~$\fooprime{\fooprime{\emph{k}}}$)}.
\begin{lisp}
(cotruncate \#Z(1 2 -3 4) \#Z(a b c)) \\*
~~{\EV} \#Z(1 2 -3) {\rm and} \#Z(a b c) \\
(until \#Z(nil nil t nil) \#Z(1 2 -3 4) \#Z(a b c)) \\*
~~{\EV} \#Z(1 2) {\rm and} \#Z(a b) \\
(until-if \#'minusp \#Z(1 2 -3 4) \#Z(a b c)) \\*
~~{\EV} \#Z(1 2) {\rm and} \#Z(a b)
\end{lisp}
\end{defun}
\begin{defun}[Function]
previous items &optional (default nil) (amount 1)
The series returned by \cdf{previous} is the same as the input series
\emph{items} except that it is shifted to the right by the positive
integer \emph{amount}. The shifting is done by inserting \emph{amount}
copies of \emph{default} before \emph{items} and discarding \emph{amount}
elements from the end of \emph{items}.
\begin{lisp}
(previous \#Z(10 11 12) 0) {\EV} \#Z(0 10 11)
\end{lisp}
\end{defun}
\begin{defun}[Function]
latch items &key :after :before :pre :post
The series returned by \cdf{latch} is the same as the input series
\emph{items} except that some of the elements are replaced by other
values. \cdf{latch} acts like a \emph{latch} electronic circuit
component. Each input element causes the creation of a corresponding
output element. After a specified number of non-null input elements
have been encountered, the latch is triggered and the output mode is
permanently changed.
The \cd{:after} and \cd{:before} arguments specify the latch point.
The latch point is just after the \cd{:after}-th non-null element in
\emph{items} or just before the \cd{:before}-th non-null element. If
neither \cd{:after} nor \cd{:before} is specified, an \cd{:after}
of \cd{1} is assumed. If both are specified, it is an error.
If a \cd{:pre} is specified, every element prior to the latch point
is replaced by this value. If a \cd{:post} is specified, every element
after the latch point is replaced by this value. If neither is
specified, a \cd{:post} of \cdf{nil} is assumed.
\begin{lisp}
(latch \#Z(nil c nil d e)) {\EV} \#Z(nil c nil nil nil) \\*
(latch \#Z(nil c nil d e) :before 2 :post t) {\EV} \#Z(nil c nil t t)
\end{lisp}
\end{defun}
\begin{defun}[Function]
collecting-fn type init function &rest series-inputs
The higher-order function \cdf{collecting-fn} supports the general concept of
a simple transducer with internal state. The \emph{type} argument is a type
specifier indicating the type of values returned by \emph{function}.
The \cdf{values} construct can be used to indicate multiple types; however,
\emph{type} cannot indicate zero values. If \emph{type} indicates $\emph{m}$ types
$\emph{t}_1, \ldots\,, \emph{t}_{m}$,
then \cdf{collecting-fn} returns $\emph{m}$ series {\it
T1},~$\ldots\,$,~\emph{Tm}, where \emph{Ti} has the
type \cd{(series~$\emph{t}_{i}$)}. The
arguments \emph{init} and \emph{function} are functions. The remaining
arguments (if any) are all series. Let these series be {\it
S1},~$\ldots\,$,~\emph{Sn} and suppose that \emph{Si} has the type
\cd{(series~$\emph{s}_{i}$)}.
The \emph{init} must be of type
\cd{(function () (values $\emph{t}_1$ ... $\emph{t}_{m}$))}.
The \emph{function} must be of type
\begin{lisp}
(function ($\emph{t}_1$ ... $\emph{t}_{m}$ $\emph{s}_1$ ... $\emph{s}_{n}$) (values $\emph{t}_1$ ... $\emph{t}_{m}$))
\end{lisp}
The length of each output is the same as the length of the shortest input.
If there are no bounded series inputs, the outputs are unbounded.
The elements of the \emph{Ti} are computed as follows:
\begin{lisp}
(values \emph{T1}\SU{0} ... \emph{Tm}\SU{0}) {\EQ} \\*
~~(multiple-value-call \emph{function} (funcall \emph{init}) \emph{S1}\SU{0} ... \emph{Sn}\SU{0}) \\
\\
(values \emph{T1}\SU{j} ... \emph{Tm}\SU{j}) {\EQ} \\*
~~(funcall \emph{function} \emph{T1}\SU{(j-1)} ... \emph{Tm}\SU{(j-1)} \emph{S1}\SU{j} ... \emph{Sn}\SU{j})
\end{lisp}
If \emph{init} or \emph{function} has side effects, it can count on
being called in the order indicated by the equations above. However,
given the lazy evaluation nature of series, these functions will not be called
until their outputs are actually used (if ever). In addition, no
assumptions can be made about the relative order of evaluation of these
calls with regard to execution in other parts of a given series expression.
The second example below computes a series of partial sums of the numbers in
an input series. The third example computes two output series: the
partial sums of its first input and the partial products of its second
input.
\begin{lisp}
(defun running-averages (float-list) \\*
~~(multiple-value-call \#'map-fn \\*
~~~~'float \#'/ \\*
~~~~(collecting-fn '(values float integer) \\*
~~~~~~~~~~~~~~~~~~~\#'(lambda () (values 0.0 0) \\*
~~~~~~~~~~~~~~~~~~~\#'(lambda (s n x) (values (+ s x) (+ n 1)))) \\*
~~~~~~~~~~~~~~~~~~~float-list)))
\end{lisp}
\begin{lisp}
(collecting-fn 'integer \#'(lambda () 0) \#'+ \#Z(1 2 3)) \\*
~~{\EV} \#Z(1 3 6) \\
\\
(collecting-fn '(values integer integer) \\*
~~~~~~~~~~~~~~~\#'(lambda () (values 0 1)) \\*
~~~~~~~~~~~~~~~\#'(lambda (sum prod x y) \\*
~~~~~~~~~~~~~~~~~~~(values (+ sum x) (* prod y))) \\*
~~~~~~~~~~~~~~~\#Z(4 6 8) \\*
~~~~~~~~~~~~~~~\#Z(1 2 3)) \\*
~~{\EV} \#Z(4 10 18) {\rm and} \#Z(1 2 6)
\end{lisp}
\end{defun}
\subsection{Conditional and Other Complex Transducers}
\label{SERIES-OL-SECTION}
This section presents a number of complex transducers, including ones that
support conditional computation.
\begin{defun}[Function]
choose bools &optional (items bools) \\
choose-if pred items
Each of these functions takes in a series of elements (\emph{items}) and
returns a series containing the same elements in the same order, but with
some elements removed. \cdf{choose} removes \emph{items}\SU{j} if {\it
bools}\SU{j} is \cdf{nil} or $\emph{j}$ is beyond the end of \emph{bools}. If {\it
items} is omitted, \cdf{choose} returns the non-null elements of {\it
bools}. \cdf{choose-if} removes \emph{items}\SU{j} if
\cd{(\emph{pred}~\emph{items}\SU{j})} is \cdf{nil}.
\begin{lisp}
(choose \#Z(t nil t nil) \#Z(a b c d)) {\EV} \#Z(a c) \\*
(collect-sum (choose-if \#'plusp \#Z(-1 2 -3 4))) {\EV} 6
\end{lisp}
\end{defun}
\begin{defun}[Function]
expand bools items &optional (default nil)
\cdf{expand} is a quasi-inverse of \cdf{choose}. The output contains the
elements of the input series \emph{items} spread out into the positions
specified by the non-null elements
in \emph{bools}---that is, \emph{items}\SU{j}
is in the position occupied by the \emph{j\/}th non-null element in \emph{bools}.
The other positions in the output are occupied by \emph{default}. The
output stops as soon as \emph{bools} runs out of elements or a non-null
element in \emph{bools} is encountered for which there is no corresponding
element in \emph{items}.
\begin{lisp}
(expand \#Z(nil t nil t t) \#Z(a b c)) {\EV} \#Z(nil a nil b c) \\*
(expand \#Z(nil t nil t t) \#Z(a)) {\EV} \#Z(nil a nil)
\end{lisp}
\end{defun}
\begin{defun}[Function]
split items &rest test-series-inputs \\
split-if items &rest test-predicates
These functions are like \cdf{choose} and \cdf{choose-if} except that
instead of producing one restricted output, they partition the input series
\emph{items} between several outputs. If there are $\emph{n}$ test inputs
following \emph{items}, then there are $\emph{n}+1$ outputs. Each input element is
placed in exactly one output series, depending on the outcome of a sequence
of tests. If the element \emph{items}\SU{j} fails the first $\emph{k}-1$ tests and
passes the \emph{k\/}h test, it is put in the \emph{k\/}th output.
If \emph{items}\SU{j}
fails every test, it is placed in the last output. In addition, all output
stops as soon as any series input runs out of elements. The test inputs to
\cdf{split} are series of values; \emph{items}\SU{j} passes the \emph{k\/}th test
if the \emph{j\/}th element of the \emph{k\/}th test series is not \cdf{nil}. The test
inputs to \cdf{split-if} are predicates; \emph{items}\SU{j} passes the \emph{k\/}th
test if the \emph{k\/}th test predicate returns non-null when applied to {\it
items}\SU{j}.
\begin{lisp}
(split \#Z(-1 2 3 -4) \#Z(t nil nil t)) \\*
~~{\EV} \#Z(-1 -4) {\rm and} \#Z(2 3) \\
(multiple-value-bind (+x -x) (split-if \#Z(-1 2 3 -4) \#'plusp) \\*
~~(values (collect-sum +x) (collect-sum -x))) \\*
~~{\EV} 5 {\rm and} -5
\end{lisp}
\end{defun}
\begin{defun}[Function]
catenate &rest series-inputs
\cdf{catenate} combines two or more series into one long series by appending
them end to end. The length of the output is the sum of the lengths of the
inputs.
\begin{lisp}
(catenate \#Z(b c) \#Z() \#Z(d)) {\EV} \#Z(b c d)
\end{lisp}
\end{defun}
\begin{defun}[Function]
subseries items start &optional below
\cdf{subseries} returns a series containing the elements of the input
series \emph{items} indexed by the non-negative integers from \emph{start} up
to, but not including, \emph{below}. If \emph{below} is omitted or greater
than the length of \emph{items}, the output goes all the way to the end
of \emph{items}.
\begin{lisp}
(subseries \#Z(a b c d) 1) {\EV} \#Z(b c d) \\*
(subseries \#Z(a b c d) 1 3) {\EV} \#Z(b c)
\end{lisp}
\end{defun}
\begin{defun}[Function]
positions bools
\cdf{positions} returns a series of the indices of the non-null elements in
the series input \emph{bools}.
\begin{lisp}
(positions \#Z(t nil t 44)) {\EV} \#Z(0 2 3)
\end{lisp}
\end{defun}
\begin{defun}[Function]
mask monotonic-indices
\cdf{mask} is a quasi-inverse of \cdf{positions}. The series input {\it
monotonic-indices} must be a strictly increasing series of non-negative
integers. The output, which is always unbounded, contains \cdf{t} in the
positions specified by \emph{monotonic-indices} and \cdf{nil} everywhere else.
\begin{lisp}
(mask \#Z(0 2 3)) {\EV} \#Z(t nil t t nil nil ...) \\*
(mask \#Z()) {\EV} \#Z(nil nil ...) \\*
(mask (positions \#Z(nil a nil b nil))) \\*
~~{\EV} \#Z(nil t nil t nil ...)
\end{lisp}
\end{defun}
\begin{defun}[Function]
mingle items1 items2 comparator
The series returned by \cdf{mingle} contains all and only the elements of
the two input series. The length of the output is the sum of the lengths
of the inputs and is unbounded if either input is unbounded. The order of
the elements remains unchanged; however, the elements from the two inputs
are stably intermixed under the control of the \emph{comparator}.
The \emph{comparator} must accept two arguments and return non-null if and only
if its first argument is strictly less than its second argument (in some
appropriate sense). At each step, the \emph{comparator} is used to compare
the current elements in the two series. If the current element from {\it
items2} is strictly less than the current element from \emph{items1}, the
current element is removed from \emph{items2} and transferred to the output.
Otherwise, the next output element comes from \emph{items1}.
\begin{lisp}
(mingle \#Z(1 3 7 9) \#Z(4 5 8) \#'<) {\EV} \#Z(1 3 4 5 7 8 9) \\*
(mingle \#Z(1 7 3 9) \#Z(4 5 8) \#'<) {\EV} \#Z(1 4 5 7 3 8 9)
\end{lisp}
\end{defun}
\begin{defun}[Function]
chunk m n items
This function has the effect of breaking up the input series \emph{items} into
(possibly overlapping) chunks of length \emph{m}. The starting positions of successive chunks differ
by \emph{n}. The inputs \emph{m} and \emph{n} must both be positive integers.
\cdf{chunk} produces \emph{m} output series. The \emph{i\/}th chunk provides
the \emph{i\/}th element for
each of the \emph{m} outputs. Suppose that the length of \emph{items} is \emph{l}.
The length of
each output is $\lfloor1+(\emph{l}-\emph{m})/\emph{n}\rfloor$.
The \emph{i\/}th element of the \emph{k\/}th output is the
$(\emph{i}*\emph{n}+\emph{k})$th element of \emph{items} (\emph{i} and $\emph{k}$ counting from zero).
Note that if $\emph{l}<\emph{m}$, there will be no
output elements, and if $\emph{l}-\emph{m}$ is not a multiple of \emph{n},
the last few input elements will
not appear in the output. If $\emph{m}\ge \emph{n}$,
one can guarantee that the last chunk will contain the last
element of \emph{items} by catenating $\emph{n}-1$
copies of an appropriate padding value to the end of \emph{items}.
The first example below shows \cdf{chunk}
being used to compute a moving average. The second example shows
\cdf{chunk} being used to convert a property list into an association list.
\begin{lisp}
(mapping (((xi xi+1 xi+2) (chunk 3 1 \#Z(1 5 3 4 5 6)))) \\*
~~(/ (+ xi xi+1 xi+2) 3)) \\*
~~{\EV} \#Z(3 4 4 5)
\\
(collect \\*
~~(mapping (((prop val) (chunk 2 2 (scan '(a 2 b 5 c 8))))) \\*
~~~~(cons prop val))) \\*
~~{\EV} ((a . 2) (b . 5) (c . 8))
\end{lisp}
\end{defun}
\subsection{Collectors}
Collectors produce non-series outputs based on series inputs. They either
create a summary value based on some formula (the sum, for example) or collect the
elements of a series in an aggregate data structure (such as a list).
\begin{defun}[Function]
collect-first items &optional (default nil) \\
collect-last items &optional (default nil) \\
collect-nth n items &optional (default nil)
Given a series \emph{items}, these functions return the first element, the
last element, and the \emph{n\/}th element, respectively. If \emph{items} has
no elements (or no \emph{n\/}th element), \emph{default} is returned.
If \emph{default} is not specified, then \cdf{nil} is used for \emph{default}.
\begin{lisp}
(collect-first \#Z() 'z) {\EV} z \\*
(collect-last \#Z(a b c)) {\EV} c \\*
(collect-nth 1 \#Z(a b c)) {\EV} b
\end{lisp}
\end{defun}
\begin{defun}[Function]
collect-length items
\cdf{collect-length} returns the number of elements in a series.
\begin{lisp}
(collect-length \#Z(a b c)) {\EV} 3
\end{lisp}
\end{defun}
\begin{defun}[Function]
collect-sum numbers &optional (type 'number)
\cdf{collect-sum} returns the sum of the elements in a series of numbers.
The \emph{type} is a type specifier that indicates the type of sum
to be created. If \emph{type} is not specified, then \cdf{number} is used for
the \emph{type}.
If there are no elements in the input, a zero (of the
appropriate type) is returned.
\begin{lisp}
(collect-sum \#Z(1.1 1.2 1.3)) {\EV} 3.6 \\*
(collect-sum \#Z() 'complex) {\EV} \#C(0 0)
\end{lisp}
\end{defun}
\begin{defun}[Function]
collect-max numbers \\
collect-min numbers
Given a series of non-complex numbers, these functions compute the maximum
element and the minimum element, respectively. If there are no elements in
the input, \cdf{nil} is returned.
\begin{lisp}
(collect-max \#Z(2 1 4 3)) {\EV} 4 \\*
(collect-min \#Z(1.2 1.1 1.4 1.3)) {\EV} 1.1 \\*
(collect-min \#Z()) {\EV} nil
\end{lisp}
\end{defun}
\begin{defun}[Function]
collect-and bools
\cdf{collect-and} returns the \cdf{and} of the elements in a series. As
with the macro \cdf{and}, \cdf{nil} is returned if any element of {\it
bools} is \cdf{nil}. Otherwise, the last element of \emph{bools} is
returned. The value \cdf{t} is returned if there are no elements in {\it
bools}.
\begin{lisp}
(collect-and \#Z(a b c)) {\EV} c \\*
(collect-and \#Z(a nil c)) {\EV} nil
\end{lisp}
\end{defun}
\begin{defun}[Function]
collect-or bools
\cdf{collect-or} returns the \cdf{or} of the elements in a series. As with
the macro \cdf{or}, \cdf{nil} is returned if every element of {\it
bools} is \cdf{nil}. Otherwise, the first non-null element of \emph{bools}
is returned. The value \cdf{nil} is returned if there are no elements in
\emph{bools}.
\begin{lisp}
(collect-or \#Z(nil b c)) {\EV} b \\*
(collect-or \#Z()) {\EV} nil
\end{lisp}
\end{defun}
\begin{defun}[Function]
collect items \\
collect type items
\cdf{collect} returns a sequence containing the elements of the series {\it
items}. The \emph{type} is a type specifier indicating the type of sequence
to be created. It must be either a proper subtype of \cdf{sequence} or the
symbol \cdf{bag}. If \emph{type} is omitted, it defaults to \cdf{list}.
(This function exhibits an argument pattern that is unusual for Common
Lisp: an ``optional'' argument preceding a required argument. This
pattern cannot be expressed in the usual manner with \cd{\&optional}. It
is indicated above by two definition lines, showing the two possible
argument patterns.)
If the \emph{type} is \cdf{bag}, a list is created with the elements in
whatever order can be most efficiently obtained. Otherwise, the order of
the elements in the sequence is the same as the order in \emph{items}. If
\emph{type} specifies a length (that is, of a vector) this length must be
greater than or equal to the length of \emph{items}.
The \emph{n\/}th element of \emph{items} is
placed in the \emph{n\/}th slot of the sequence produced. Any unneeded slots are
left in their initial state. Collecting is significantly more efficient if
it can be determined at compile time whether \emph{type} is a subtype of
\cdf{list} or \cdf{vector} and for vectors what the length of the vector is.
\begin{lisp}
(collect \#Z(a b c)) {\EV} (a b c) \\*
(collect 'bag \#Z(a b c)) {\EV} (c a b) {\rm or} (b a c) {\rm or $\ldots$} \\*
(collect '(vector integer 3) \#Z(1 2 3)) {\EV} \#(1 2 3)
\end{lisp}
\end{defun}
\begin{defun}[Function]
collect-append sequences \\
collect-append type sequences