-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.lisp
executable file
·3053 lines (2737 loc) · 112 KB
/
core.lisp
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
;;;; Hey, Emacs, this is a -*- Mode: Lisp; Syntax: Common-Lisp -*- file!
;;;;
;;;; Programming should be fun. Programs should be beautiful.
;;;; -- Paul Graham
;;;;
;;;; Name: core.lisp
;;;;
;;;; Started: Fri Jan 6 19:06:25 2006
;;;; Modifications:
;;;;
;;;; Purpose:
;;;;
;;;;
;;;;
;;;; Calling Sequence:
;;;;
;;;;
;;;; Inputs:
;;;;
;;;; Outputs:
;;;;
;;;; Example:
;;;;
;;;; Notes:
;;;; Needs work: MAPTUPLES
;;;;
(eval-when (:compile-toplevel :load-toplevel :execute)
#+ :sbcl (load "/home/slytobias/lisp/packages/collections" :verbose nil)
#- :sbcl (load "/home/slytobias/lisp/packages/collections.lisp" :verbose nil))
(defpackage :core
(:shadowing-import-from :collections :intersection :set :subsetp :union)
(:use :common-lisp :collections)
(:export :after :append1 :analyze-tree :approximately= :array-indices :as-if
:before :best :best-index :best-worst :best-worst-n :bestn :build-prefix :build-tree
:>case :class-template :comment :compose :conc1 :copy-array :cycle
:defchain :destructure :dohash :doset :dostring :dotuples :dovector
:drop :drop-until :drop-while :duplicatep
:emptyp :ends-with :equalelts :equals :eqls :every-pred :explode
:filter :filter-split :find-some-if :find-subtree :firsts-rests :for :flatten
:group :group-until :horners
:if-let :if3 :iffn :in :in-if :inq :is-integer :iterate
:juxtapose
:last1 :least :leastn :list-to-string :longerp
:macroexpand-all :make-empty-seq :make-identity-matrix
:map-> :map-array :map-array-index :map0-n :map1-n :mapa-b :mapcars :mappend :mapset
:memoize :mklist :mkstr :most :mostn :most-least :most-least-n :nif
:partial :partial* :partition :ppmx
:prefix-generator :prefixp :prune :prune-if :prune-if-not
:range :repeat :rmapcar
:rotate0 :rotate-list0 :rotate1 :rotate-list1
:same-shape-tree-p
:shift0 :shift-list0 :shift1 :shift-list1
:show-symbols :shuffle :singlep :some-pred :sort-symbol-list :splice
; :split-if
:stable-partition :starts-with :stream-partition :suffixp :symb
:take :take-drop :take-while :take-until :totally :transfer
:transition :transition-1 :transition-n :transition-stream :traverse :tree-find-if :tree-map
:until
:when-let :when-let* :while :with-gensyms :worst :worstn)
(:shadow :emptyp :next))
; (:shadow :while :until :prefixp :dovector :macroexpand-all)) ; ????
(in-package :core)
(proclaim '(inline last1 singlep append1 conc1 mklist))
(defmacro comment (&body body)
(declare (ignore body)))
;;;
;;; Seibel pg. 101
;;;
;; (defmacro with-gensyms ((&rest names) &body body)
;; `(let ,(loop for n in names
;; collect `(,n (gensym)))
;; ,@body))
;;;
;;; Seibel's downloadable code is slightly different:
;;;
;; (defmacro with-gensyms ((&rest names) &body body)
;; `(let ,(loop for n in names collect `(,n (make-symbol ,(string n))))
;; ,@body))
;; (defmacro with-gensyms ((&rest names) &body body)
;; `(let ,(loop for n in names
;; collect `(,n (make-symbol ,(symbol-name n))))
;; ,@body))
;;;
;;; Should it be called WITH-GENSYMS if it uses MAKE-SYMBOL???
;;;
(defmacro with-gensyms ((&rest names) &body body)
`(let ,(loop for n in names
collect `(,n ',(make-symbol (symbol-name n)))) ; ??
,@body))
;;;
;;; Splice a new sequence into another.
;;; (Works like Perl splice()/substr())
;;; Extend to vectors too?
;;;
;;; This is slightly different than Perl in that the new elements are
;;; expected to be bundled into a sequence (list or string) rather than
;;; passed as separate args. This is done to accommodate both lists and
;;; strings in a uniform way.
;;;
(defun splice (seq &optional (offset 0) (length (length seq)) new-seq)
"Splice a subsequence into a given sequence at a specified location."
(if (minusp offset)
(if (> (abs offset)
(length seq))
(setf offset 0)
(setf offset (+ (length seq) offset))))
(if (minusp length)
(if (< (+ (length seq) length)
offset)
(setf length 0)
(setf length (- (+ (length seq) length)
offset))))
(let ((seq-type (typecase seq
(string 'string)
(list 'list))))
(concatenate seq-type
(subseq seq 0 offset)
new-seq
(subseq seq (min (length seq) (+ offset length)))) ))
;;;
;;; Create a list of successive integers from START to END.
;;; (Like Perl's (START..END))
;;; See below...
; (defun make-range (&optional (start 0) (end 0))
; (if (> start end)
; (rotatef start end))
; (mapcar #'(lambda (x)
; (setf x start)
; (incf start)
; x)
; (make-list (1+ (- end start)))) )
;;;
;;; Convert NIL to ()
;;;
(defun list-to-string (l)
(labels ((list-to-string-aux (obj stream)
(cond ((atom obj) (format stream "~S" obj))
(t (destructuring-bind (head . tail) obj
(if (listp head)
(format stream "~A" (list-to-string head))
(list-to-string-aux head stream))
(unless (null tail)
(if (atom tail)
(format stream " . ")
(format stream " "))
(list-to-string-aux tail stream)))) )))
(if (listp l)
(with-output-to-string (out)
(format out "(")
(unless (null l)
(list-to-string-aux l out))
(format out ")"))
l)))
;; (defun list-to-string (l)
;; (labels ((list-to-string-aux (obj stream)
;; (cond ((atom obj) (format stream "~S" obj))
;; (t (if (listp (first obj))
;; (format stream "~A" (list-to-string (first obj)))
;; (list-to-string-aux (car obj) stream))
;; (unless (null (cdr obj))
;; (format stream " ")
;; (list-to-string-aux (cdr obj) stream)))) ))
;; (if (listp l)
;; (with-output-to-string (out)
;; (format out "(")
;; (unless (null l)
;; (list-to-string-aux l out))
;; (format out ")"))
;; l)))
;;;
;;; Pascal Bourguignon
;;;
(defun show-symbols (package-name)
(do-external-symbols (s package-name)
(when (fboundp s)
(format t "~40A : ~A~%" s
(cond
((special-operator-p s) "special-operator")
((macro-function s) "macro")
(t "function"))))
(when (boundp s)
(format t "~40A : ~A~%" s
(cond
((constantp s) "constant variable")
(t "variable")))) ))
;;;
;;; This is slightly different than the version below. If (> i (length l))
;;; this returns NIL for REMOVED.
;;;
;;; It also builds a completely new list for the REMAINDER.
;;;
(defun transfer (seq i)
"Remove the ith element from a sequence, returning the element and the new sequence."
(typecase seq
(list (loop for elt in seq
for j from 0
unless (= i j) collect elt into remainder
when (= i j) collect elt into removed
finally (return (values (first removed) remainder))))
(string (let ((result (make-string (1- (length seq)))))
(setf (subseq result 0 i) (subseq seq 0 i)
(subseq result i) (subseq seq (1+ i)))
(values (elt seq i) result)))
(vector (let ((result (make-array (1- (length seq)))) )
(setf (subseq result 0 i) (subseq seq 0 i)
(subseq result i) (subseq seq (1+ i)))
(values (elt seq i) result)))) )
;; (defun transfer (seq i)
;; "Remove the ith element from a sequence, returning the element and the new sequence."
;; (typecase seq
;; (list (loop for elt in seq
;; for j from 0
;; unless (= i j) collect elt into remainder
;; when (= i j) collect elt into removed
;; finally (return (values (first removed) remainder))))
;; (vector (let ((result (make-sequence (type-of seq) (1- (length seq))))) ; <---- Doesn't work. Shorter vector is different type...
;; (setf (subseq result 0 i) (subseq seq 0 i)
;; (subseq result (1+ i)) (subseq seq (1+ i)))
;; (values (elt seq i) result)))) )
;; (defun transfer (l i)
;; "Remove the ith element from a list, returning the element and the new list."
;; (loop for elt in l
;; for j from 0
;; unless (= i j) collect elt into remainder
;; when (= i j) collect elt into removed
;; finally (return (values (first removed) remainder))))
;; (defun transfer (l i)
;; "Remove the ith element from a list, returning the element and the new list."
;; (let* (removed
;; (remainder (loop for elt in l
;; for j from 0
;; unless (= i j) collect elt
;; when (= i j) do (setf removed elt))))
;; (values removed remainder)))
;;;
;;; Surprisingly (?) the tail-recursive version is faster than the iterative
;;; version. (Because of the extra AND test on every loop?)
;;; The naive version is the slowest. It does the most CONSing. The other
;;; two do less (the same amount, in fact).
;;;
;;; Note: The new list returned may share structure with the original!
;;;
;; (defun transfer (l i)
;; "Remove the ith element from a list, returning the element and the new list."
;; (labels ((transfer-aux (l i result)
;; (cond ((null l) (error "Could not transfer element"))
;; ((zerop i) (values (car l)
;; (append (nreverse result) (cdr l))))
;; (t (transfer-aux (cdr l)
;; (1- i)
;; (cons (car l) result)))) ))
;; (transfer-aux l i '())))
; (defun transfer-a (l i)
; (let ((elt (nth i l)))
; (values elt (remove elt l :start i :count 1))))
; (defun transfer-b (l i)
; "Remove the ith element from a list, returning the element and the new list."
; (do ((result '() (cons (car list) result))
; (list l (cdr list))
; (index i (1- index)))
; ((and list (zerop index)) (values (car list)
; (append (nreverse result) (cdr list))))
; (when (null list)
; (error "Could not transfer element"))))
(defgeneric drop (n seq)
(:documentation "Drop the first N elements of sequence SEQ."))
(defmethod drop (n (seq list))
(nthcdr n seq))
(defmethod drop (n (seq vector))
(subseq seq (min n (length seq))))
(defgeneric take (n seq)
(:documentation "Take the first N elements of sequence SEQ."))
(defmethod take (n (seq list))
(loop repeat n for elt in seq collect elt))
(defmethod take (n (seq vector))
(subseq seq 0 (min n (length seq))))
(defgeneric take-drop (n seq)
(:documentation "Split a sequence at the Nth element. Return the subsequences before and after."))
(defmethod take-drop :around (n seq)
(assert (typep n `(integer 0))
(n)
"N must be a non-negative integer.")
(call-next-method))
(defmethod take-drop (n (seq list))
(do ((tail seq (rest tail))
(i 0 (1+ i)))
((or (= i n) (endp tail))
(if (endp tail)
(values seq '())
(values (subseq seq 0 i) tail)))) )
(defmethod take-drop (n (seq vector))
(values (take n seq) (drop n seq))) ; Works for strings too
;;;
;;; Why is this so hard to get right?!?
;;; - Problem cases: N = 0, N > length
;;; (Inconsistency with CLISP???)
;;;
;; (defun take-drop (n seq)
;; "Split a sequence at the Nth element. Return the subsequences before and after."
;; (assert (typep n `(integer 0))
;; (n)
;; "N must be a non-negative integer.")
;; (typecase seq
;; (list (if (zerop n) ;<-- Unnecessary when using queue explicitly. Only needed with LOOP version?
;; (values '() seq)
;; (loop for i from 0 below n
;; for elt in seq
;; for tail on seq
;; collect elt into q
;; do (print (list i elt q tail))
;; finally (return (values q #- :clisp (rest tail) #+ :clisp tail))) ))
;; (vector (values (take n seq) (drop n seq)))) ) ; Works for strings too
;; (defun take-drop (n seq)
;; (loop repeat n
;; for elt in seq
;; for tail on (rest seq)
;; collect elt into take
;; finally (return (values take tail))))
;;;
;;; Call TAKE-WHILE, get DROP-WHILE for free.
;;;
(defgeneric take-while (pred seq)
(:documentation "Take elements of sequence SEQ until PRED evaluates to false. Return remainder of sequence as secondary value."))
(defmethod take-while (pred (seq list))
(loop for tail on seq
for elt in seq
while (funcall pred elt)
collect elt into result
finally (return (values result tail))))
(defmethod take-while (pred (seq vector))
(take-drop (or (position-if-not pred seq) (length seq)) seq))
(defun take-until (pred seq)
(take-while (complement pred) seq))
(defgeneric drop-while (pred seq)
(:documentation "Drop elements of sequence SEQ until PRED evaluates to false."))
(defmethod drop-while (pred (seq list))
(loop for tail on seq
for elt in seq
while (funcall pred elt)
finally (return tail)))
(defmethod drop-while (pred (seq vector))
(drop (or (position-if-not pred seq) (length seq)) seq))
(defun drop-until (pred seq)
(drop-while (complement pred) seq))
;; (defun empty-seq (in)
;; (map (type-of in) #'identity in))
;; (defun empty-seq (in)
;; (make-sequence (type-of in) 0))
(defun make-empty-seq (in)
(typecase in
(list (list))
(string (make-string 0))
(vector (vector))))
(defun prefix-generator (l)
"Given a list L return a function that successively yields all prefixes of L."
(let ((q (make-linked-queue))
(list l))
#'(lambda ()
(prog1 (copy-list (elements q))
(if (endp list)
(make-empty q)
(enqueue q (pop list)))) )))
;; pathname, structure, hash table, bit vector
(defgeneric equals (o1 o2)
(:documentation "Is O1 equal to O2 in a type-specific sense?"))
(defmethod equals (o1 o2)
(eql o1 o2))
(defmethod equals ((n1 number) (n2 number))
(= n1 n2))
(defmethod equals ((s1 string) (s2 string))
(string= s1 s2))
(defmethod equals ((ch1 character) (ch2 character))
(char= ch1 ch2))
(defmethod equals ((l1 list) (l2 list))
(cond ((null l1) (null l2))
((null l2) nil)
((equals (first l1) (first l2)) (equals (rest l1) (rest l2)))
(t nil)))
(defmethod equals ((v1 vector) (v2 vector))
(if (= (length v1) (length v2))
(do ((i 0 (1+ i)))
((= i (length v1)) t)
(unless (equals (aref v1 i) (aref v2 i))
(return nil)))) )
(defmethod equals ((s1 symbol) (s2 symbol))
(equals (symbol-name s1) (symbol-name s2)))
;; (defmethod equals ((k1 keyword) (k2 keyword))
;; (call-next-method))
;; pathname, structure, hash table, bit vector
(defgeneric eqls (o1 o2)
(:documentation "Is O1 EQL to O2 or are all elements EQL?"))
(defmethod eqls (o1 o2)
(eql o1 o2))
(defmethod eqls ((s1 string) (s2 string))
(string= s1 s2))
(defmethod eqls ((l1 list) (l2 list))
(cond ((null l1) (null l2))
((null l2) nil)
((eqls (first l1) (first l2)) (eqls (rest l1) (rest l2)))
(t nil)))
(defmethod eqls ((v1 vector) (v2 vector))
(if (= (length v1) (length v2))
(do ((i 0 (1+ i)))
((= i (length v1)) t)
(unless (eqls (aref v1 i) (aref v2 i))
(return nil)))) )
(defgeneric prefixp (s1 s2 &key test)
(:documentation "Is sequence S1 a prefix of S2?"))
(defmethod prefixp ((v1 vector) (v2 vector) &key (test #'eql))
(let ((length1 (length v1)))
(if (>= (length v2) length1)
(let ((index (mismatch v1 v2 :test test)))
(or (null index) (= index length1)))
nil)))
(defmethod prefixp ((l1 list) (l2 list) &key (test #'eql))
(cond ((null l1) t)
((null l2) nil)
((funcall test (first l1) (first l2)) (prefixp (rest l1) (rest l2) :test test))
(t nil)))
;;;
;;; (prefixp (reverse l1) (reverse l2)) !!!!
;;;
(defgeneric suffixp (s1 s2 &key test)
(:documentation "Is sequence S1 and suffix of S2?"))
(defmethod suffixp ((v1 vector) (v2 vector) &key (test #'eql))
(if (>= (length v2) (length v1))
(let ((index (mismatch v1 v2 :test test :from-end t)))
(or (null index) (zerop index)))
nil))
;; (defmethod suffixp ((l1 list) (l2 list) &key (test #'eql))
;; (labels ((match1 (l1 l2)
;; (cond ((null l1) (null l2))
;; ((null l2) nil)
;; ((funcall test (first l1) (first l2))
;; (or (match2 (rest l1) (rest l2))
;; (match1 l1 (rest l2))))
;; (t (match1 l1 (rest l2)))) )
;; (match2 (l1 l2)
;; (cond ((null l1) (null l2))
;; ((null l2) nil)
;; ((funcall test (first l1) (first l2))
;; (match2 (rest l1) (rest l2)))
;; (t nil))))
;; (or (null l1) (match1 l1 l2))))
(defmethod suffixp ((l1 list) (l2 list) &key (test #'eql))
(cond ((null l2) (null l1))
((not (mismatch l1 l2 :test test)))
(t (suffixp l1 (rest l2) :test test))))
(defun starts-with (s1 s2 &key (test #'eql))
(prefixp s2 s1 :test test))
(defun ends-with (s1 s2 &key (test #'eql))
(suffixp s2 s1 :test test))
;---------------Macros------------------------
;; (defmacro while (test &body body)
;; `(do ()
;; ((not ,test))
;; ,@body) )
(defmacro while (test &body body)
`(loop (unless ,test (return))
,@body))
;; (defmacro while (test &body body)
;; `(loop while ,test
;; do ,@body))
;; (defmacro while (test &body body)
;; (let ((tag (gensym)))
;; `(block nil
;; (tagbody
;; ,tag
;; (unless ,test (return))
;; ,@body
;; (go ,tag)))) )
;; (defmacro until (test &body body)
;; `(do ()
;; (,test)
;; ,@body) )
(defmacro until (test &body body)
`(loop (when ,test (return))
,@body) )
;;;
;;; Don't (declare (ignore ,i))!!
;;; The macro doesn't use it directly, but DOTIMES does!
;;;
(defmacro repeat (count &body body)
(with-gensyms (i)
`(dotimes (,i ,count)
,@body)))
;; (defmacro repeat (count &body body)
;; (if (null body)
;; nil
;; `(loop repeat ,count
;; do ,@body)))
;; (defmacro repeat (count &body body)
;; `(loop repeat ,count
;; do ,@body))
;; (defmacro dovector ((var vector &optional result) &body body)
;; (let ((v (gensym))
;; (l (gensym))
;; (i (gensym)))
;; `(do* ((,v ,vector)
;; (,l (length ,v))
;; (,i 0 (1+ ,i))
;; ,var)
;; ((= ,i ,l) ,result)
;; (setf ,var (aref ,v ,i))
;; ,@body)))
(defmacro dovector ((var vector &optional result) &body body)
(with-gensyms (v l i)
`(do* ((,v ,vector)
(,l (length ,v))
(,i 0 (1+ ,i)))
((= ,i ,l) ,result)
(let ((,var (aref ,v ,i)))
,@body))))
;;;
;;; Disallow crosstalk w/ LOOP keywords in BODY?
;;; Binding of VARS should be available in RESULT... This is consistent with DOLIST but not very useful?
;;;
;; (defmacro dotuples ((vars l &optional result) &body body)
;; (with-gensyms (list rest)
;; `(do ((,list ,l))
;; ((endp ,list) ,result)
;; (destructuring-bind (,@vars . ,rest) ,list
;; ,@body
;; (setf ,list ,rest)))) )
(defmacro dotuples ((vars l &optional result) &body body)
"Iterate over list L consuming VARS variables on each iteration. The bindings of these variables are visible in BODY."
`(loop for ,vars on ,l by #'(lambda (l) (nthcdr ,(length vars) l))
do ,@body
finally (return ,result)))
;;;
;;; Kind of weird? VARS specifies variable bindings, but there is no body in which they are visible...
;;;
;; (defmacro maptuples (f vars l)
;; "Map the function F over the list L, consuming VARS variables on each iteration.
;; If the length of L is not a multiple of the number of VARS, then some variables will be assigned NIL on the final iteration."
;; `(loop for ,vars on ,l by #'(lambda (l) (nthcdr ,(length vars) l))
;; collect (funcall ,f ,@vars)))
(defun maptuples (f n l)
"Map function F over list L, consuming N elements on each invocation."
(mapcar #'(lambda (args) (apply f args)) (group l n)))
;;;
;;; Cosmetic changes to Graham's DO-TUPLES/O
;;;
(defmacro open-path (vars source &body body)
(if vars
(with-gensyms (src)
`(let ((,src ,source))
(mapc #'(lambda ,vars ,@body)
,@(map0-n #'(lambda (n)
`(nthcdr ,n ,src))
(1- (length vars)))) ))
nil))
;;;
;;; Derived from my DOTUPLES above
;;; Graham's is more elegant.
;;;
;; (defmacro open-path (vars source &body body)
;; (with-gensyms (src rest)
;; `(do ((,src ,source (rest ,src)))
;; (nil)
;; (destructuring-bind (,@vars . ,rest) ,src
;; ,@body
;; (when (null ,rest)
;; (return)))) ))
;; (macroexpand-1 '(do-tuples/o (x y) '(a b c d) (print (list x y))))
;; (PROG ((#:G4225 '(A B C D)))
;; (MAPC #'(LAMBDA (X Y) (PRINT (LIST X Y)))
;; (NTHCDR 0 #:G4225)
;; (NTHCDR 1 #:G4225)))
;; T
;; * (macroexpand-1 '(open-path (x y) '(a b c d) (print (list x y))))
;; (LET ((#:SRC '(A B C D)))
;; (MAPC #'(LAMBDA (X Y) (PRINT (LIST X Y))) (NTHCDR 0 #:SRC) (NTHCDR 1 #:SRC)))
;; T
;;; CLOSED-PATH
(defmacro do-tuples/c (parms source &body body)
(if parms
(with-gensyms (src rest bodfn)
(let ((len (length parms)))
`(let ((,src ,source))
(when (nthcdr ,(1- len) ,src)
(labels ((,bodfn ,parms ,@body))
(do ((,rest ,src (cdr ,rest)))
((not (nthcdr ,(1- len) ,rest))
,@(mapcar #'(lambda (args)
`(,bodfn ,@args))
(dt-args len rest src))
nil)
(,bodfn ,@(map1-n #'(lambda (n)
`(nth ,(1- n)
,rest))
len))))))))))
(defun dt-args (len rest src)
(map0-n #'(lambda (m)
(map1-n #'(lambda (n)
(let ((x (+ m n)))
(if (>= x len)
`(nth ,(- x len) ,src)
`(nth ,(1- x) ,rest))))
len))
(- len 2)))
;; (defmacro dostring ((ch string &optional result) &body body)
;; (let ((s (gensym))
;; (l (gensym))
;; (i (gensym)))
;; `(do* ((,s ,string)
;; (,l (length ,s))
;; (,i 0 (1+ ,i))
;; ,ch)
;; ((= ,i ,l) ,result)
;; (setf ,ch (char ,s ,i))
;; ,@body)))
(defmacro dostring ((ch string &optional result) &body body)
(with-gensyms (s l i)
`(do* ((,s ,string)
(,l (length ,s))
(,i 0 (1+ ,i)))
((= ,i ,l) ,result)
(let ((,ch (char ,s ,i)))
,@body))))
;; (defmacro dostring ((ch s &optional result) &body body)
;; `(dovector (,ch ,s ,result)
;; ,@body))
;; (defmacro dostring ((ch s &optional result) &body body)
;; (let ((res (gensym)))
;; `(let ((,res ,result))
;; (loop for ,ch across ,s
;; do ,@body)
;; (or ,res nil))))
(defmacro dohash (((key val) hash &optional result) &body body)
(with-gensyms (next more)
`(with-hash-table-iterator (,next ,hash)
(loop (multiple-value-bind (,more ,key ,val) (,next)
(unless ,more (return ,result))
,@body)))) )
(defmacro doset ((elt set &optional result) &body body)
`(dolist (,elt (elements ,set) ,result)
,@body))
;; (defmacro doset ((elt set &optional result) &body body)
;; (let ((next (gensym))
;; (more (gensym))
;; (val (gensym)))
;; `(with-hash-table-iterator (,next ,set)
;; (loop (multiple-value-bind (,more ,elt ,val) (,next)
;; (declare (ignore ,val))
;; (unless ,more (return ,result))
;; ,@body)))) )
;;;
;;; Should be (defun mapset (f &rest sets)?
(defun mapset (f set)
(let ((result (make-set :test (hash-table-test (slot-value set 'elements)))) )
(doset (elt set)
(add-elt result (funcall f elt)))
result))
;---------------Touretzky------------------------
(defmacro ppmx (form)
"Pretty prints the macro expansion of FORM."
`(let* ((exp1 (macroexpand-1 ',form))
(exp (macroexpand exp1))
(*print-circle* nil))
(cond ((equal exp exp1)
(format t "~&Macro expansion:")
(pprint exp))
(t (format t "~&First step of expansion:")
(pprint exp1)
(format t "~2%Final expansion:")
(pprint exp)))
(format t "~2%")
(values)))
;---------------Graham On Lisp------------------------
(defun last1 (l)
(first (last l)))
(defun singlep (l)
(and (consp l) (null (rest l))))
(defun append1 (l obj)
(append l (list obj)))
(defun conc1 (l obj)
(nconc l (list obj)))
(defun mklist (obj)
(if (listp obj)
obj
(list obj)))
;; (defgeneric mklist (obj))
;; (defmethod mklist (obj) (list obj))
;; (defmethod mklist ((l list)) l)
;;;
;;; Graham calls this LONGER. I believe this is inappropriate since this
;;; function does not return the 'longer' of the two sequences. Rather, it
;;; simply tests whether SEQ1 is longer than SEQ2.
;;;
;; (defun longerp (seq1 seq2)
;; "Is SEQ1 strictly longer than SEQ2?"
;; (labels ((compare (seq1 seq2)
;; (cond ((endp seq1) nil)
;; ((endp seq2) t)
;; (t (compare (rest seq1) (rest seq2)))) ))
;; (if (and (listp seq1) (listp seq2))
;; (compare seq1 seq2)
;; (> (length seq1) (length seq2)))) )
;; (defun longerp (seq1 seq2)
;; "Is SEQ1 strictly longer than SEQ2?"
;; (labels ((compare-ll (seq1 seq2)
;; (cond ((endp seq1) nil)
;; ((endp seq2) t)
;; (t (compare-ll (rest seq1) (rest seq2)))) )
;; (compare-ln (seq n)
;; (cond ((endp seq) nil)
;; ((zerop n) t)
;; (t (compare-ln (rest seq) (1- n)))) )
;; (compare-nl (n seq)
;; (cond ((zerop n) nil)
;; ((endp seq) t)
;; (t (compare-nl (1- n) (rest seq)))) ))
;; (cond ((and (listp seq1) (listp seq2)) (compare-ll seq1 seq2))
;; ((listp seq1) (compare-ln seq1 (length seq2)))
;; ((listp seq2) (compare-nl (length seq1) seq2))
;; (t (> (length seq1) (length seq2)))) ))
(defgeneric longerp (seq1 seq2)
(:documentation "Is SEQ1 strictly longer than SEQ2?"))
(defmethod longerp ((seq1 list) (seq2 list))
(cond ((endp seq1) nil)
((endp seq2) t)
(t (longerp (rest seq1) (rest seq2)))) )
(defmethod longerp ((seq1 list) (seq2 sequence))
(labels ((compare (seq n)
(cond ((endp seq) nil)
((zerop n) t)
(t (compare (rest seq) (1- n)))) ))
(compare seq1 (length seq2))))
(defmethod longerp ((seq1 sequence) (seq2 list))
(labels ((compare (n seq)
(cond ((zerop n) nil)
((endp seq) t)
(t (compare (1- n) (rest seq)))) ))
(compare (length seq1) seq2)))
(defmethod longerp ((seq1 sequence) (seq2 sequence))
(> (length seq1) (length seq2)))
;;;
;;; This collects the _values_ of applying the function to elts, not
;;; the elts themselves. Different from REMOVE-IF-NOT!
;;;
;;; More efficient version of: (mapcar #'f (remove-if-not #'f seq))
;;; FILTER uses the result of applying F to determine which elements to keep.
;;;
;; (defun filter (f seq)
;; (typecase seq
;; (list (loop for elt in seq
;; for val = (funcall f elt)
;; when val collect val))
;; (vector (loop for elt across seq
;; for val = (funcall f elt)
;; when val collect val into result
;; finally (return (coerce result (if (stringp seq) 'string 'vector)))) )))
(defgeneric filter (f seq)
(:documentation "Retain non-nil values obtained by applying F to elts of SEQ."))
(defmethod filter (f (seq list))
(loop for elt in seq
for val = (funcall f elt)
when val collect val))
(defmethod filter (f (seq sequence))
(loop for elt across seq
for val = (funcall f elt)
when val collect val))
(defmethod filter (f (seq vector))
(coerce (call-next-method) 'vector))
(defmethod filter (f (seq string))
(coerce (call-next-method) 'string))
;;;
;;; See matrix::list-to-rows-fill-rows
;;;
;; (defun group (source n)
;; (when (zerop n) (error "Invalid length."))
;; (labels ((group-aux (source acc)
;; (let ((rest (nthcdr n source)))
;; (if (consp rest)
;; (group-aux rest (cons (subseq source 0 n) acc))
;; (nreverse (cons source acc)))) ))
;; (if source
;; (group-aux source '())
;; '())))
(defun emptyp (seq)
(typecase seq
(list (null seq))
(vector (zerop (length seq)))) )
;;;
;;; See Clojure partition-all
;;;
;; (defun group (seq n)
;; (loop for take-drop = (multiple-value-list (take-drop n seq))
;; then (multiple-value-list (take-drop n (second take-drop)))
;; until (emptyp (first take-drop))
;; collect (first take-drop)))
;;;
;;; Must terminate when (EMPTYP TAKE) to handle N = 0.
;;;
(defun group (seq n)
(loop for (take drop) = (multiple-value-list (take-drop n seq))
then (multiple-value-list (take-drop n drop))
until (emptyp take)
collect take))
;;;
;;; This is even slower
;;;
;; (defun group (seq n)
;; (do ((result (make-linked-queue))
;; (row (make-linked-queue))
;; (l seq (rest l))
;; (i 0 (1+ i)))
;; ((emptyp l) (unless (collections:emptyp row)
;; (enqueue result (elements row)))
;; (elements result))
;; (when (= i n)
;; (setf i 0)
;; (enqueue result (elements row))
;; (make-empty row))
;; (enqueue row (first l))))
;;;
;;; The semantics here seem wrong since the reversed list is tested but then flipped around when included in the result.
;;; That may actually be irrelevant here since the TIPPING-POINT function normally tests the subsequence as a set, i.e.,
;;; independent of its ordering.
;;;
;; (defun group-until-list (tipping-point seq)
;; "Group elements of SEQ into a subsequence until TIPPING-POINT returns true for that subsequence, then start next subsequence."
;; (let ((groups (reduce #'(lambda (groups elt)
;; (destructuring-bind (current . result) groups
;; (if (funcall tipping-point (cons elt current)) ; Reversed list is tested??
;; (cons (list elt) (cons (nreverse current) result)) ; But flipped for result???
;; (cons (cons elt current) result))))
;; seq
;; :initial-value (cons '() '()))) )
;; (destructuring-bind (current . result) groups
;; (nreverse (cons (nreverse current) result)))) )
;;;
;;; The above version is faster than these 2, presumably due to CLOS below.
;;; The persistant-queue version is surprisingly competitive to the rollback version.
;;; I expected that the ELEMENTS method for the persistent-queue would sink it.
;;;
;;; It does appear to slow down as the length of the accumulated subsequence grows:
;;; (defvar *l* (loop repeat 800 collect (random 20)))
;;; (time (dotimes (i 10000) (GROUP-UNTIL #'(LAMBDA (L) (> (REDUCE #'+ L) 20)) *l*)))
;;; (time (dotimes (i 10000) (GROUP-UNTIL-persistent #'(LAMBDA (L) (> (REDUCE #'+ L) 20)) *l*)))
;;;
;;; vs.
;;;
;;; (time (dotimes (i 10000) (GROUP-UNTIL #'(LAMBDA (L) (> (REDUCE #'+ L) 100)) *l*)))
;;; (time (dotimes (i 10000) (GROUP-UNTIL-persistent #'(LAMBDA (L) (> (REDUCE #'+ L) 100)) *l*)))
;;;
(defun group-until-persistent (tipping-point seq)
"Group elements of SEQ into a subsequence until TIPPING-POINT returns true for that subsequence, then start next subsequence."
(let ((groups (reduce #'(lambda (groups elt)
(destructuring-bind (current . result) groups
(if (funcall tipping-point (elements (enqueue current elt)))
(cons (enqueue (make-persistent-queue) elt) (enqueue result (elements current)))
(cons (enqueue current elt) result))))
seq
:initial-value (cons (make-persistent-queue) (make-persistent-queue)))) )
(destructuring-bind (current . result) groups
(elements (enqueue result (elements current)))) ))
;; (defun group-until (tipping-point seq)
;; "Group elements of SEQ into a subsequence until TIPPING-POINT returns true for that subsequence, then start next subsequence."
;; (let ((groups (reduce #'(lambda (groups elt)
;; (destructuring-bind (current . result) groups
;; (enqueue current elt)
;; (if (funcall tipping-point (elements current))
;; (let ((new-current (make-rollback-queue)))
;; (rollback current)
;; (enqueue result (elements current))
;; (enqueue new-current elt)
;; (cons new-current result))
;; (cons current result))))
;; seq
;; :initial-value (cons (make-rollback-queue) (make-linked-queue)))) )
;; (destructuring-bind (current . result) groups
;; (elements (enqueue result (elements current)))) ))
;;;
;;; All of the fat trimmed off...
;;;
(defun group-until (tipping-point seq)
"Group elements of SEQ into a subsequence until TIPPING-POINT returns true for that subsequence, then start next subsequence."
(let ((groups (reduce #'(lambda (groups elt)
(destructuring-bind (current . result) groups
(enqueue current elt)
(when (funcall tipping-point (elements current))
(rollback current)
(enqueue result (elements current))
(make-empty current)
(enqueue current elt))
groups))
seq
:initial-value (cons (make-rollback-queue) (make-linked-queue)))) )
(destructuring-bind (current . result) groups
(elements (enqueue result (elements current)))) ))
;; (defun flatten (tree)
;; (labels ((flatten-aux (tree result)
;; (cond ((null tree) (nreverse result))
;; ((null (car tree)) (flatten-aux (cdr tree) result))
;; ((atom (car tree)) (flatten-aux (cdr tree) (cons (car tree) result)))
;; (t (flatten-aux (list* (caar tree) (cdar tree) (cdr tree)) result)))) )
;; (if (atom tree)
;; tree
;; (flatten-aux tree '()))) )
(defun flatten (tree)
(labels ((flatten-aux (tree result)