-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathseq-apis.lisp
More file actions
2413 lines (2115 loc) · 94.5 KB
/
seq-apis.lisp
File metadata and controls
2413 lines (2115 loc) · 94.5 KB
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
(in-package :clj-coll)
;;;; Clojure APIs that mostly return lazy seqs, and M function equivalents.
;;;; See also seq-apis2.lisp for stuff which requires doseq.
;;;; M functions (see README.md) that correspond to lazy functions are placed in
;;;; proximity to their namesakes.
(defvar *debug-transducers* nil
"If non-nil, break on entry to transducers")
;; Debugging crap
(eval-when (:compile-toplevel :load-toplevel :execute)
;; Because I really don't want to pass the name of the function in which transducer macros
;; are called just for debugging I should never need once I get things working.
(defun env-function-name (env)
"Try to ascertain the name of the function in which &environment ENV exists.
:cl-environment doesn't have a thing for this that I know of, whatever
is done here is surely unportable.
STRICTLY A SHORT TERM DEBUGGING TOOL FOR SBCL + TRANSDUCER MACROS
Returns \"<UNKNOWN-FUNCTION>\" if it can't figure it out."
(declare (ignorable env))
(let ((unknown "<ENV-FUNCTION-NAME UNKNOWN>"))
#+sbcl ;#<SB-KERNEL:LEXENV> structure object
(if env
(-> (slot-value env 'sb-c::blocks) caar symbol-name)
unknown)
#-sbcl
unknown)))
(defmacro transducer ((rf result input) &body body &environment env)
"emit code that defines a transducer, taking care of the multiple-arity
function skeleton, using parameter names indicated by rf, result, and input.
the expansion has to the basic clojure transducer shape (as equivalent common lisp):
(fn [rf]
(fn ([] (rf)) ;arity0 - init
([result] (rf result)) ;arity1 - completion for some stateful transducers
([result input] <body>))) ;arity2 - so-called 'step' function, the meaningful bits
body is used as the body of the arity2 function signature.
If you need to specify a greater arity than 2, because your logic requires multiple
inputs (e.g. `map`), you'll have to hand code it, or this macro would have to be made to
accommodate multiple bodies for the different arities.
See the single-argument FILTER signature for an example use of this macro.
See also: STATEFUL-TRANSDUCER.
"
(let ((xfargs (gensym "xfargs-"))
(function-name (env-function-name env)))
`(lambda (,rf)
(lambda (&rest ,xfargs)
(when *debug-transducers*
(format t "~%~a transducer args: ~s~%" ,function-name ,xfargs))
(ecase (cl:length ,xfargs)
(0 (funcall ,rf)) ;init
(1 (let ((,result (cl:first ,xfargs))) ;completion
(funcall ,rf ,result)))
(2 (let ((,result (cl:first ,xfargs)) ;step
(,input (cl:second ,xfargs)))
,@body)))))))
(defmacro stateful-transducer ((rf result input state-vars
&key init-body completion-body)
&body step-body &environment env)
;; This macro may or may not be better than simply typing all the nested lambdas.
;; But the arity-expression is still better.
"Like 'transducer' except it provides parameters for state variable declaration,
initialization code, and completion code, as well as the customary step body.
STATE-VARS should be a list of variable names or variable/init sublists as if for LET.
(fn [rf]
(let ((<state1> <init1>) ;state vars
...)
(fn ([] (rf)|<init-body>) ;arity0 - initialization
([result] (rf result)|<completion-body>) ;arity1 - completion
([result input] <step-body>)))) ;arity2 - step
INIT-BODY and COMPLETION-BODY are optional and default to the behavior of the
`TRANSDUCER` macro if unspecified.
"
(let ((xfargs (gensym "xfargs-"))
(init-body (or init-body `(funcall ,rf)))
(completion-body (or completion-body `(funcall ,rf ,result)))
(function-name (env-function-name env)))
`(lambda (,rf)
(let (,@state-vars)
(lambda (&rest ,xfargs)
(when *debug-transducers*
(format t "~%~a stateful transducer args: ~s~%" ,function-name ,xfargs))
(case (cl:length ,xfargs)
(0 ,init-body)
(1 (let ((,result (cl:first ,xfargs)))
,completion-body))
(2 (let ((,result (cl:first ,xfargs))
(,input (cl:second ,xfargs)))
,@step-body))))))))
(defun count-while (pred coll)
"Return the count of leading items in COLL for which (PRED item) returns true.
Don't confuse with COUNT-IF which would continue searching and possibly counting
after a NIL value from PRED."
(let ((c 0)
(pred (alexandria:ensure-function pred)))
(declare (function pred))
(run! (lambda (item)
(if (funcall pred item)
(incf c)
(return-from count-while c)))
coll)
c))
(defun mfilter (pred coll)
"An eager version of FILTER that returns a CL:LIST
of all items in COLL for which (PRED item) returns true.
Will realize lazy sequences, don't pass an infinite sequence!
See also CL:REMOVE-IF-NOT."
(let ((pred (alexandria:ensure-function pred)))
(declare (function pred))
(if (cl:listp coll)
(cl:remove-if-not pred coll)
(alexeum:with-collector (collect)
(run! (lambda (item)
(when (funcall pred item)
(collect item)))
coll)))))
(defn-ish filter
"([pred] [pred coll])
Returns a lazy sequence of the items in COLL for which
(PRED item) returns true.
Phrased another way: (REMOVE-IF-NOT PRED COLL).
PRED should be free of side-effects.
Returns a transducer when no collection is provided.
See also: MFILTER, REMOVE, CL:REMOVE-IF-NOT."
((pred)
(transducer (rf result input)
(if (funcall pred input)
(funcall rf result input)
result)))
((pred coll)
(lazy-seq
(when-let (s (seq coll))
(let ((first (first s)))
(if (funcall pred first)
(cons first (filter pred (rest s)))
(filter pred (rest s))))))))
(defun filterv (pred coll)
"([pred coll])
Returns a persistent or mutable vector having the same mutability trait as COLL,
consisting of items in COLL for which (PRED item) returns true. PRED should be free
of side-effects."
(let* ((result (make-v coll))
(pusher (make-pusher result))
(pred (alexandria:ensure-function pred)))
(declare (function pred))
(run! (lambda (val)
(when (funcall pred val)
(funcall pusher val)))
coll)
result))
(defn-ish mtake
"([n coll] [result-type n coll])
An eager version of TAKE that will return a CL:LIST(default) or
CL:VECTOR of N elements from COLL (which may be a seq), returning all items in coll
if there are fewer than N.
The optional leading RESULT-TYPE parameter may be one of the symbols CL:LIST or
CL:VECTOR, and behaves as if CL:LIST were specified if RESULT-TYPE is omitted.
No structure is shared with COLL.
(MTAKE 0) returns NIL for CL:LIST returns and #() for CL:VECTOR returns."
((n coll) (mtake 'cl:list n coll))
((result-type n coll)
(ecase result-type
(cl:list
(loop repeat n
for s = (seq coll) then (next s)
while s
collect (first s)))
(cl:vector
(if (<= n 0)
#()
(loop with result = (make-array n :fill-pointer 0)
repeat n
for s = (seq coll) then (next s)
while s
do (vector-push (first s) result)
finally (return result)))))))
(defn-ish mtake-while
"([pred coll] [result-type pred coll])
An eager version of TAKE that will return a CL:LIST(defualt) or CL:VECTOR
of leading elements from COLL (which may be a seq) for which (PRED item) returns true.
If there are no items matched by PRED or COLL is empty, CL:LIST result will be NIL
and CL:VECTOR result will be #().
Results may share structure (or be EQ) with CL:SEQUENCE inputs."
((pred coll) (mtake-while 'cl:list pred coll))
((result-type pred coll)
(let ((pred (alexandria:ensure-function pred)))
(declare (function pred))
(ecase result-type
(cl:list
;; No attempt at sharing a fully matched input CL:LIST
(loop for s = (seq coll) then (next s)
as val = (first s)
while (and s (funcall pred val))
collect val))
(cl:vector
(let ((n-matched (count-while pred coll)))
(if (zerop n-matched)
#()
(let* ((sharing (cl:vectorp coll))
(result (if sharing
(if (= n-matched (cl:length coll))
coll ;EQ result
(make-array n-matched :displaced-to coll))
(make-array n-matched))))
(if sharing
result ;no need to copy vals
(loop for i from 0
for s = (seq coll) then (next s)
as val = (first s)
while (and s (funcall pred val))
do (setf (svref result i) val)
finally (return result)))))))))))
(defn-ish take
"([n] [n coll])
Returns a lazy sequence of the first n items in coll, or all items if
there are fewer than n. Returns a stateful transducer when
no collection is provided. The transducer is not thread-safe.
See also: MTAKE"
((n)
(transducer (rf result input)
(let ((result (if (plusp n)
(funcall rf result input)
result)))
(if (not (plusp (decf n)))
(ensure-reduced result)
result))))
((n coll)
(lazy-seq
(when (plusp n)
(when-let (s (seq coll))
(cons (first s) (take (1- n) (rest s))))))))
(defn-ish take-while
"([pred] [pred coll])
Returns a lazy sequence of successive items from coll while
(pred item) returns true. pred must be free of side-effects.
Returns a transducer when no collection is provided."
((pred)
(transducer (rf result input)
(if (funcall pred input)
(funcall rf result input)
(ensure-reduced result))))
((pred coll)
(lazy-seq
(when-let (s (seq coll))
(let ((item (first s)))
(when (funcall pred item)
(cons item (take-while pred (rest s)))))))))
(defn-ish take-nth
"([n] [n coll])
Returns a lazy seq of every item in COLL whose ordinal sequence position is
such that (= 0 (REM I N)) for some position I. This means the first item
is always returned.
E.g.
(take-nth 2 (range 6)) => (0 2 4)
(take-nth 3 (range 6)) => (0 3)
Returns a stateful transducer when no collection is provided.
For the [N COLL] arity, values of N <= 0 will result in an infinite sequence.
For the transducer, values of N <= 0 will signal an error.
See also MTAKE-NTH. There is no DROP-NTH ... because regularly occurring
values of a collection are only interesting, never uninteresting?"
((n)
(when (<= n 0)
(error "Values of N <= 0 are not valid for the TAKE-NTH transducer."))
(stateful-transducer (rf result input ((i 0)))
(prog1
(if (= 0 (rem i n))
(funcall rf result input)
result)
(incf i))))
((n coll)
(lazy-seq
(when-let (s (seq coll))
(cons (first s) (take-nth n (drop n s)))))))
(defun mtake-nth (n coll)
"An eager, CL:LIST returning version of TAKE-NTH.
N must be positive."
(if (<= n 0)
(error "Values of N <= 0 are not valid for MTAKE-NTH.")
(loop for i from 0
for s = (seq coll) then (next s)
while s
when (= 0 (rem i n))
collect (first s))))
(defn-ish mdrop
"([n coll] [result-type n coll])
An eager version of DROP that returns CL:LIST(default) or CL:VECTOR, and may share
structure if COLL is a compatible type.
You may optionally specify a RESULT-TYPE leading argument
to control the returned type. It should be a symbol which is one of
CL:LIST, CL:VECTOR, or :BEST. The first two specify the
type to be returned.
If :BEST is given, MDROP will select for the
most efficient of the CL:LIST and CL:VECTOR types and should be
treated by the caller as returning a CL:SEQUENCE.
If N is zero, returns the whole collection with the indicated RESULT-TYPE.
The return value may be EQ the input value if result and collection types are compatible.
If N exceeds the number of elements in COLL, return NIL for CL:LIST RESULT-TYPE, and
an empty CL:VECTOR otherwise.
Do not pass an infinite sequence!
See also: DOSEQ (for polymorphic processing of CL:SEQUENCE types)."
((n coll) (mdrop 'cl:list n coll))
((result-type n coll)
(check-type n integer)
(when (< n 0)
(setf n 0))
(ecase result-type
(:best
(if (cl:vectorp coll)
(mdrop 'cl:vector n coll)
(if (cl:listp coll)
(mdrop 'cl:list n coll)
(if (counted? coll)
(mdrop 'cl:vector n coll)
;; We could count here on an O(n) coll
;; If we ask for cl:vector it will count _again_
;; (unless we pass it in with special variable)
;; but may be better to use for large collection
;; For now we go with a list.
(mdrop 'cl:list n coll)))))
(cl:list ;wants a list
(typecase coll
(cl:list (cl:nthcdr n coll))
(cl:vector
(let ((size (- (cl:length coll) n)))
(if (> size 0)
(loop for j from n below (cl:length coll)
collect (aref coll j))
nil)))
(t ;suppose we could mconcat...
(loop for i from 0
for s = (seq coll) then (next s)
while s
when (>= i n)
collect (first s)))))
(cl:vector ;wants a vector
(typecase coll
(cl:vector
(let ((size (- (cl:length coll) n)))
(if (> size 0)
(if (= n 0)
coll
(make-array size :displaced-to coll :displaced-index-offset n))
#())))
(cl:list
(let ((size (- (cl:length coll) n)))
(if (> size 0)
(loop with result = (make-array size)
for i from 0
for val in (cl:nthcdr n coll)
do (setf (svref result i) val)
finally (return result))
#())))
(t
;; Could be smarter avoiding seqs on fset:seq here, perhaps another day
(if-let (s (nthnext (seq coll) n))
(mconcat 'cl:vector s)
#())))))))
(defn-ish mdrop-while
"([pred coll] [result-type pred coll])
An eager CL-collection-returning version of DROP-WHILE.
Returns items in COLL following the leading items for which (PRED item) returns true,
returns all items if PRED always returns false.
Returns either a CL:LIST(default) or CL:VECTOR, depending on the
presence of the optional RESULT-TYPE argument, which must be one of 'CL:LIST
or 'CL:VECTOR.
If PRED matches all items, returns NIL for a CL:LIST result, or #() for a CL:VECTOR
result.
Results may share data with CL:LIST and CL:VECTOR COLLs, including
being EQ with coll if PRED filters no items.
Lazy seqs are fully realized, don't pass infinite sequences."
((pred coll) (mdrop-while 'cl:list pred coll))
((result-type pred coll)
(let ((pred (alexandria:ensure-function pred)))
(declare (function pred))
(flet ((generic-mdrop ()
(loop for s = (seq coll) then (next s)
while (and s (funcall pred (first s)))
finally (return (if s
(mconcat result-type s)
(if (eq result-type 'cl:list)
nil
#()))))))
(ecase result-type
(cl:list
(if (cl:listp coll) ;we can share list structure
(loop for cons on coll
while (funcall pred (car cons))
finally (return cons))
(generic-mdrop)))
(cl:vector
(if (cl:vectorp coll) ;we can share vector structure
(loop with len = (cl:length coll)
for i from 0 below len
while (funcall pred (aref coll i))
finally
(return
(if (= i len)
#()
(if (= i 0)
coll
(make-array (- len i)
:displaced-to coll
:displaced-index-offset i)))))
(generic-mdrop))))))))
(defn-ish drop
"([n] [n coll])
Returns a laziness-preserving sequence of all but the first n items in coll.
Returns a stateful transducer when no collection is provided.
The returned transducer is not safe for concurrent use by multiple threads."
((n)
(transducer (rf result input)
(if (plusp n)
(progn (decf n)
result) ;ignoring input, changing state
(funcall rf result input))))
((n coll)
(lazy-seq
(loop for s = (seq coll) then (next s)
for i from n above 0
while s
finally (return s)))))
(defn-ish drop-while
"([pred] [pred coll])
Returns a lazy sequence of the items in coll following leading items
for which (pred item) returns true. Returns a
stateful transducer when no collection is provided.
The returned transducer is not safe for concurrent use by multiple threads."
((pred)
(stateful-transducer (rf result input
((dropping? t)))
(if dropping?
(if (funcall pred input)
result ;drop input
(progn (setf dropping? nil) ;no longer dropping
(funcall rf result input))) ;include input
(funcall rf result input))))
((pred coll)
(lazy-seq
(loop for s = (seq coll) then (next s)
while (and s (funcall pred (first s)))
finally (return (or s *EMPTY-LIST*))))))
(defun applycat (coll colls)
"Helper for concat, takes one collection/seq, and possibly empty list of collections/seqs"
(lazy-seq
(if-let (s (seq coll))
(cons (first s) (applycat (next s) colls)) ;iterating through first coll
(when-let (coll (first colls)) ;ready for next coll
(when-let (s (seq coll))
(cons (first s) (applycat (next s) (rest colls))))))))
(defn-ish concat
"([] [coll] [coll1 coll2] [coll1 coll2 & colls])
Return a lazy seq representing the concatenation of the elements in the supplied colls."
(()
(lazy-seq nil))
((coll)
(lazy-seq coll))
((coll1 coll2)
(lazy-seq
(if-let (s (seq coll1))
(cons (first s) (concat (rest s) coll2))
coll2)))
((coll1 coll2 & colls)
(applycat (concat coll1 coll2) colls)))
(defun clj-apply (f &rest args)
"A substitute for CL:APPLY if your last argument is not a CL:LIST.
Converts the last argument, which must be some kind of CLJ-COLL supported collection,
to a CL:LIST if necessary, then invokes CL:APPLY.
Tip: MCONCAT will convert your non-cl:list collection into a cl:list.
Design decision: don't shadow CL:APPLY, we don't really want to encourage
use of this more expensive apply. Thus the name CLJ-APPLY.
The need arises only rarely because all CL functions already have CL:LIST
&rest lists. Note that you can also use M functions
to give you a CL:LIST result in many cases."
;; Unfortunately, by this (CLJ-APPLY) indirection on apply
;; can't use the args list even if the last element was a cl:list.
;; 'args' becomes our new arglist and tail collection must be
;; flattened into 'args'.
(let* ((lastcons (cl:last args))
(lastarg (first lastcons))
(args (cl:butlast args)))
(if (null lastarg)
(cl:apply f args)
(if (collp lastarg)
(apply f (mconcat 'cl:list args (convert 'cl:list lastarg)))
(error "Last argument ~s must be a collection." lastarg)))))
(defun mapcat (f &rest colls)
"([f] [f & colls])
Applies CONCAT to the result of (MAP F COLLS).
Return the lazy result.
F should return a collection.
Example:
(flet ((add1 (&rest nums) (mapv #'1+ nums)))
(mapcat #'add1 [1 2 3] [4 5 6]))
=> (2 5 3 6 4 7)
Returns a transducer when no collections are provided."
(if colls
(clj-apply #'concat (apply #'map f colls))
;; Remember comp is effectively executed left to right when
;; given transducers. Too clever by half, credit to Clojure.
(comp (map f) #'cat)))
(defun mmapcat (&rest args)
"([f & colls]) [result-type f & colls])
An eager version of MAPCAT that returns a CL:LIST(default) or CL:VECTOR
as indicated by the optional RESULT-TYPE which must be one of those symbols.
If the result is an empty collection, returns NIL for CL:LIST RESULT-TYPE
or #() for CL:VECTOR result-type.
Applies MCONCAT to the result of (MMAP F COLLS).
F should return a collection.
Example:
(flet ((add1 (&rest nums) (mapv #'1+ nums)))
(mmapcat #'add1 [1 2 3] [4 5 6]))
=> (2 5 3 6 4 7)
There is no transducer arity, use MAPCAT instead."
(let* ((nargs (cl:length args))
(first (cl:first args))
(second (cl:second args))
(result-type-p (and (>= nargs 2)
first (symbolp first)
second (or (symbolp second)
(functionp second))))
(result-type (if result-type-p first 'cl:list))
(f (if result-type-p second first))
(colls (if result-type-p (cddr args) (cdr args))))
(if colls
(apply #'mconcat result-type
;; Has to be lists for apply unless we get smarter about it
(apply #'mmap 'cl:list f colls))
(if (eq 'cl:list result-type)
nil
#()))))
(declaim (ftype (function (t t) (values cl:vector &optional)) copyseq-to-vector))
(defun copyseq-to-vector (type colls)
"Helper routine for mconcat to copy colls to a vector type."
(let* ((n (loop for coll in colls summing (count coll)))
(result (ecase type
(cl:string (make-string n))
(cl:simple-vector (make-array n))
(cl:vector (make-array n :adjustable t :fill-pointer n))))
(index 0))
(declare (fixnum index))
;; We're not really taking advantage of optimizations on RESULT type
;; We _are_ avoiding arrayseq consing.
(loop for coll in colls
do (typecase coll
(cl:vector
(loop for item across coll
do (setf (aref result index) item)
(incf index)))
(cl:list
(loop for item in coll
do (setf (aref result index) item)
(incf index)))
(fset:seq
(fset:do-seq (item coll)
(setf (aref result index) item)
(incf index)))
(t
(loop for s = (seq coll) then (next s)
while s
do (setf (aref result index) (first s))
(incf index)))))
result))
(declaim (ftype (function (t) (values cl:list &optional)) copyseq-to-list))
(defun copyseq-to-list (colls)
"Helper routine for mconcat to copy colls to a list."
(alexeum:with-collector (result)
(loop for coll in colls
do (typecase coll
(cl:vector
(loop for item across coll
do (result item)))
(cl:list
(loop for item in coll
do (result item)))
(t
(loop for s = (seq coll) then (next s)
while s
do (result (first s))))))))
(defun mconcat (&rest optional-result-type-and-colls)
"(result-type? colls*) ; pattern syntax for illustration
Concatenate zero or more colls, with an optional RESULT-TYPE symbol as the first
argument. An eager alternative to CONCAT that produces only CL:LIST(default) or
CL:VECTOR results (while still being able to traverse all CLJ-COLL collections &
seqs).
If there are no elements in collections, returns NIL for CL:LIST results,
or an empty CL:VECTOR if CL:VECTOR was the requested return types.
This is a brute force concatenation, ALL collections are copied,
even if you only pass one an it's already of the desired result type.
Thus the result is safe to modify without destroying any inputs.
This function is similar to a CLJ-COLL-aware CL:CONCATENATE, though
there are some interpretations of RESULT-TYPE that differ, including no regard
for some possible subtypes of CL:LIST and CL:VECTOR.
The supported types and semantics here are:
- CL:LIST - self evident
- CL:VECTOR - a fill-pointered adjustable vector
- CL:SIMPLE-VECTOR - a simple vector (no fill-pointer, not adjustable,
elements of type T)
- CL:STRING - a string as with MAKE-STRING, in which case colls
had better be strings or contain characters.
Unlike CL:CONCATENATE RESULT-TYPE is optional.
Unlike CONCAT, an optional RESULT-TYPE is permitted."
(let* ((type (when-let (x (first optional-result-type-and-colls))
(and (symbolp x) x)))
(colls (if type
(cl:rest optional-result-type-and-colls)
optional-result-type-and-colls))
(type (or type 'cl:list)))
(if (subtypep type 'cl:vector)
(copyseq-to-vector type colls)
(if (eq type 'cl:list)
(copyseq-to-list colls)
(error "Unsupported result type ~s" type)))))
(defn-ish range
"([] [start] [start end] [start end step])
Returns a lazy seq of nums from START (inclusive) to END
(exclusive), by STEP, where START defaults to 0, STEP to 1, and END to
infinity. When STEP is equal to 0, returns an infinite sequence of
START. When START is equal to END, returns an empty list.
Clojure compatibility note: Common Lisp doesn't really have a representation
for numeric infinity. An end value of NIL will be treated as infinity
in whatever direction STEP moves START."
;; Note that CLojure's range could return clojure.lang.Repeat objects.
;; We have no intention of emulating such artifacts.
(()
(range 0 nil 1))
((end)
(range 0 end 1))
((start end)
(range start end 1))
((start end step)
(flet ((done? ()
(if end
(if (< step 0)
(<= start end)
(>= start end))
nil)))
(lazy-seq
(if (done?)
nil
(cons start (range (+ start step) end step)))))))
(defun mrange (&rest args)
"([result-type* start end] [result-type* start end step])
An eager version of RANGE returning a CL:LIST(default) or CL:VECTOR
of numbers from START (inclusive) to END (exclusive),
by the optional STEP which defaults to 1.
An optional leading RESULT-TYPE argument may be one of the symbols
CL:LIST or CL:VECTOR to specify the desired return type.
MRANGE does not permit obvious attempts at returning infinite
sequences. END is a required argument, and error is signalled if STEP is zero.
When START is equal to END, returns nil for CL:LIST return types,
and #() for CL:VECTOR return types."
;; I hated to mess up this arg list by adding optional leading result-type, and do
;; this only for consistency with other M functions, but we lose compile-time
;; checks and and there's no good valid-lambda-list expression of this that reads
;; well.
(when (< (cl:length args) 2)
(error "(mrange result-type* start end &optional step), missing args"))
(let* ((result-type-p (and (cl:first args) (symbolp (cl:first args))))
(result-type (if result-type-p (cl:first args) 'cl:list))
(args (if result-type-p (cdr args) args))
(start (cl:first args))
(end (cl:second args))
(step (or (cl:third args) 1)))
(unless (member result-type '(cl:list cl:vector))
(error "Invalid result-type specification: ~s, must be cl:list or cl:vector."
result-type))
(when (zerop step)
(error "Step must not be zero. For infinite sequences use RANGE."))
(let ((result (make-collector result-type)))
(if (< step 0)
;; Couldn't figure out how to loop BY a negative step
;; without a sbcl type warning.
(do ((i start (+ i step)))
((<= i end))
(collect result i))
(loop for i from start below end by step
do (collect result i)))
(grab result))))
(defun mpartition (n &rest args)
"([n coll & kwargs] [n step coll & kwargs] [n step pad coll & kwargs])
This is an eager version of PARTITION that returns a CL:LIST(default)
or CL:VECTOR with options for both the top level result type
and the partition-type.
Differences from PARTITION:
- This performs O(1n) iterations on the input, not O(4n) (assuming STEP = N).
- All returned collection types are CL collections.
- A NIL/empty collection results in NIL (not an empty lazy-seq).
- STEP and N must be >= 1 to avoid infinite sequences.
- NIL is a valid empty PAD collection.
- NIL is a valid empty COLL.
- COLL should not be an infinite sequence, or anything else that
would blow out memory if all its elements were materialized.
- The type of result and the type of the partitions may be specified.
This function has the same argument signature as PARTITION except that
for any arity you may specify optional kwargs to control
the type of sequences returned. The valid key/vey pairs are:
:result-type CL:LIST|CL:VECTOR
:partition-type CL:LIST|CL:VECTOR
The default for both collection types is CL:LIST.
See also: PARTITION, PARTITIONV, PARTITION-ALL, PARTITIONV-ALL"
;; Grand experiment, this was a real pain in the ass to write
;; compared to one using first/next/mtake/mdrop, but does pay dividends
;; if the input is an array or some type that 'seq'ing on would cons a lot.
(let* ((step-p (integerp (cl:first args)))
(step (if step-p (cl:first args) n))
(args (if step-p (cdr args) args))
(pad-p (and (>= (cl:length args) 2) ;for pad and coll
(not (keywordp (cl:first args)))
(not (keywordp (cl:second args)))))
(pad (when pad-p (cl:first args)))
(args (if pad-p (cdr args) args))
;; There must be a coll in PARTITION, no transdcuer arity
(coll-p (and (>= (cl:length args) 1)
;; colls, strings, nil all seqable, but strings aren't collp or coll?
(seqable? (cl:first args))))
(coll (when coll-p (cl:first args)))
(kwargs (if coll-p (cdr args) args))
(result-type (cl:getf kwargs :result-type 'cl:list))
(partition-type (cl:getf kwargs :partition-type 'cl:list)))
(unless coll-p
(error "Missing collection argument"))
(when (<= step 0)
(error "Step must be greater than zero, not ~s" step))
(when (<= n 0)
(error "N must be greater than zero, not ~s" n))
(check-list-or-vector-result-type :result-type result-type)
(check-list-or-vector-result-type :partition-type partition-type)
(when (empty? coll)
(return-from mpartition nil))
;; And away we go. COLL is not empty. Must respect pad-p to know whether
;; NIL is an empty PAD collection or just a stub for a no-pad-supplied invocation
;; Minor *PERFORMANCE*: allow non-adjustable vectors with make-collector, use
;; svref on them. Requires we do the reallocations on growth-oriented APIs like
;; ASSOC/CONJ
;; Here we use iterators instead of first/next to avoid seq consing
;; Much tricker to write than using seqs and mtake/mdrop, particularly for the
;; step<N case.
;; Although if COLL is a seq we haven't optimized anything.
;; All this work is only optimal if COLL is a _collection_ to be
;; traversed by the iterator code (which optimizes for collection type).
(let* ((result-collector (make-collector result-type :size n))
(partition-collector (make-collector partition-type :size n))
(eof #1=':eof)
(colliter (iterator coll eof))
(partition-item-count 0)
;; if skip < n, buffer values we'll need to re-read
(step-delta (max (- n step) 0))
(buffered (1+ step-delta))
(step-read-count 0)
;; ringqueue holes exactly step-delta elements
;; But needs +1 because of how we read and trigger rereads
(rq (when (plusp step-delta) (ring-queue buffered))))
(declare (fixnum step-read-count partition-item-count step-delta buffered))
(labels ((next-value ()
(if (plusp step-read-count)
(progn (decf step-read-count) (rq-get rq))
(funcall colliter))))
(do ((item (next-value)))
((eq item eof))
(if (< partition-item-count n)
(progn (collect partition-collector item)
(incf partition-item-count)
;; Each element in partition goes into ringqueue
;; which is sized to discard elements we won't reuse for next partition
(when rq (rq-put rq item))
(setf item (next-value)))
;; Partition complete
(progn (collect result-collector (grab-safe partition-collector))
(reset partition-collector)
(setf partition-item-count 0)
;; Does this item begin next partition, or do we need
;; to STEP forward/backward?
(cond ((= step n)) ;NOOP: re-execute loop with currently pending item
((> step n) ;discard item, step forward to next
(setf item (iterator-skip colliter (- step n) eof)))
(t ;step back, reread buffer, re-execute loop with reused item
(setf step-read-count buffered)
(rq-put rq item)
(setf item (next-value)))))))
;; collect final (possibly incomplete) partition
(if (= partition-item-count n)
(collect result-collector (grab partition-collector))
(when (and (> partition-item-count 0) pad-p)
(loop repeat (- n partition-item-count)
for s = (seq pad) then (next s)
while s
while (< partition-item-count n)
do (collect partition-collector (first s))
(incf partition-item-count)
finally
;; partial partition possible because we have pad
(if (>= partition-item-count 1)
(collect result-collector (grab partition-collector))))))
(grab result-collector)))))
#+(OR)
;; This one really wasn't too bad, but it is 2-3x slower on consing arrayseqs
;; Anyway, just a comparison for my notes.
(defn-ish mpartition
"([n coll] [n step coll] [n step pad coll])
Like PARTITION, only all partitions are eagerly computed, and the resulting top level
list and all partition subsequences are CL:LISTs.
A STEP <= 0 is will return only the first partition, unlike the infinite sequence
that would result from PARTITION.
N <= 0 will return NIL, unlike PARTITION which returns an infinite sequence."
;; Must use seqs instead of iterator because STEP values may require backtracking if
;; smaller than partition size N. To use iterators would require caching materialized
;; values and indexing them.
((n coll) (mpartition n n coll))
((n step coll)
(when (<= n 0)
(return-from mpartition nil))
(if (<= step 0)
(cl:list (mtake n coll))
(loop for s = (seq coll) then (nthrest s step)
as partition = (mtake n s)
while (= n (cl:length partition))
collect partition)))
((n step pad coll)
(when (<= n 0)
(return-from mpartition nil))
(if (<= step 0)
(cl:list (mtake n coll))
(loop for s = coll then (nthnext s step)
while s
as partition = (mtake n s)
if (= n (cl:length partition))
collect partition
else
collect (mtake n (mconcat partition pad))))))
(defn-ish partition
"([n coll] [n step coll] [n step pad coll])
Returns a lazy sequence of lists of N items each,
drawn from elements of COLL at OFFSETS items apart.
If STEP is not supplied, defaults to N, and the partitions
do not overlap. If a PAD collection is supplied, use its elements as
necessary to complete last partition upto n items. If there are
not enough padding elements, return a partition with fewer than N items.
Note that if _no_ PAD is supplied, there is no case where partitions
with fewer than N are returned.
Coded for Clojure compatibility, with up to 4N seq traversals. Ouch.
See also: MPARTITION (1N), PARTITIONV (2N)."
;; Pretty much Clojure's algorithm to give you
;; realized lazy-seq partitions for semantic compatibility.
;; with all the associated inefficiencies.
((n coll)
(partition n n coll))
((n step coll)
(lazy-seq
(when-let (s (seq coll))
;; doall for clojure semantics, partitions should be realized
(let ((partition (doall (take n s)))) ;kerching, 2N, and lazy to boot
(when (= n (count partition)) ;kerching 3N
(cons partition (partition n step (nthrest s step)))))))) ;kerching 4N
((n step pad coll)
(lazy-seq
(when-let (s (seq coll))
(let ((partition (take n s)))
(if (= n (count partition))
(cons partition (partition n step pad (nthrest s step)))
(list (take n (concat partition pad)))))))))
(defn-ish partitionv
"([n coll] [n step coll] [n step pad coll])
Basically the same as PARTITION except that the partitions are vectors
instead of realized lazy sequences.
Returns a lazy sequence of vectors of n items each, at offsets step
apart. If step is not supplied, defaults to n, i.e. the partitions
do not overlap. If a pad collection is supplied, use its elements as
necessary to complete last partition upto n items. In case there are
not enough padding elements, return a partition with less than n items.
See also: MPARTITION."
((n coll)
(partitionv n n coll))
((n step coll)
(lazy-seq
(when-let (s (seq coll))
(let ((partition (into (vector) (take n) s)))
(when (= n (count partition))
(cons partition (partitionv n step (nthrest s step))))))))
((n step pad coll)
(lazy-seq
(when-let (s (seq coll))
(let ((partition (into (vector) (take n) s)))