-
Notifications
You must be signed in to change notification settings - Fork 7
/
stuff.scm
2256 lines (1967 loc) · 78.2 KB
/
stuff.scm
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
;; some useful (or at least amusing) functions and macros
(provide 'stuff.scm)
(when (provided? 'pure-s7)
(define (let->list e) (reverse! (map values e))))
;;; ----------------
(define empty?
(let ((documentation "(empty? obj) returns #t if obj is an empty sequence"))
(lambda (obj)
(and (not (pair? obj))
(if (hash-table? obj)
(zero? (hash-table-entries obj)) ; length here is table size
(eqv? (length obj) 0))))))
(define applicable? arity)
;(define sequence? length) -- now built-in for procedure-signatures
(define indexable?
(let ((documentation "(indexable? obj) returns #t if obj can be applied to an index: (obj 0)"))
(lambda (obj)
(and (sequence? obj)
(applicable? obj)))))
(define (ow!)
(call-with-output-string
(lambda (p)
(let ((ow (owlet))
(elist (list (rootlet))))
;; show current error data
(format p "error: ~A" (ow 'error-type))
(let ((info (ow 'error-data)))
(if (and (pair? info)
(string? (car info)))
(format p ": ~A" (apply format #f info))
(if (not (null? info))
(format p ": ~A" info))))
(format p "~%error-code: ~S~%" (ow 'error-code))
(when (ow 'error-line)
(format p "~%error-file/line: ~S[~A]~%" (ow 'error-file) (ow 'error-line)))
;; show history, if available
(when (pair? (ow 'error-history)) ; a circular list, starts at error-code, entries stored backwards
(let ((history ())
(lines ())
(files ())
(start (ow 'error-history)))
(do ((x (cdr start) (cdr x))
(i 0 (+ i 1)))
((or (eq? x start)
(null? (car x))
(= i (*s7* 'history-size)))
(format p "~%error-history:~% ~S" (car start))
(do ((x history (cdr x))
(line lines (cdr line))
(f files (cdr f)))
((null? x))
(format p (if (and (integer? (car line))
(string? (car f))
(not (string=? (car f) "*stdout*")))
(values "~% ~S~40T;~A[~A]" (car x) (car f) (car line))
(values "~% ~S" (car x)))))
(format p "~%"))
(set! history (cons (car x) history))
(set! lines (cons (pair-line-number (car x)) lines))
(set! files (cons (pair-filename (car x)) files)))))
;; show the enclosing contexts
(let ((old-print-length (*s7* 'print-length)))
(set! (*s7* 'print-length) 8)
(do ((e (outlet ow) (outlet e)))
((memq e elist)
(set! (*s7* 'print-length) old-print-length))
(if (> (length e) 0)
(format p "~%~{~A~| ~}~%" e))
(set! elist (cons e elist))))))))
#|
(set! (hook-functions *error-hook*)
(list (lambda (hook)
(apply format *stderr* (hook 'data))
(newline *stderr*)
(when ((owlet) 'error-line)
(format *stderr* "~S line ~A~%" ((owlet) 'error-file) ((owlet) 'error-line)))
(do ((e (outlet (owlet)) (outlet e)))
((eq? e (rootlet)))
(format *stderr* "~{ ~A~%~}~%" e))
(format *stderr* "~%~A~%" (stacktrace)))))
|#
;;; ----------------
(define (first obj) (if (sequence? obj) (obj 0) (error 'wrong-type-arg "first argument, ~S, is not a sequence" obj)))
(define (second obj) (if (sequence? obj) (obj 1) (error 'wrong-type-arg "second argument, ~S, is not a sequence" obj)))
(define (third obj) (if (sequence? obj) (obj 2) (error 'wrong-type-arg "third argument, ~S, is not a sequence" obj)))
(define (fourth obj) (if (sequence? obj) (obj 3) (error 'wrong-type-arg "fourth argument, ~S, is not a sequence" obj)))
(define (fifth obj) (if (sequence? obj) (obj 4) (error 'wrong-type-arg "fifth argument, ~S, is not a sequence" obj)))
(define (sixth obj) (if (sequence? obj) (obj 5) (error 'wrong-type-arg "sixth argument, ~S, is not a sequence" obj)))
(define (seventh obj)(if (sequence? obj) (obj 6) (error 'wrong-type-arg "seventh argument, ~S, is not a sequence" obj)))
(define (eighth obj) (if (sequence? obj) (obj 7) (error 'wrong-type-arg "eighthment, ~S, is not a sequence" obj)))
(define (ninth obj) (if (sequence? obj) (obj 8) (error 'wrong-type-arg "ninth argument, ~S, is not a sequence" obj)))
(define (tenth obj) (if (sequence? obj) (obj 9) (error 'wrong-type-arg "tenth argument, ~S, is not a sequence" obj)))
(define iota
(let ((documentation "(iota n (start 0) (incr 1)) returns a list counting from start for n:\n\
(iota 3) -> '(0 1 2)"))
(lambda* (n (start 0) (incr 1))
(if (or (not (integer? n))
(< n 0))
(error 'wrong-type-arg "iota length ~A should be a non-negative integer" n))
(let ((lst (make-list n)))
(do ((p lst (cdr p))
(i start (+ i incr)))
((null? p) lst)
(set! (car p) i))))))
(define (cdr* lst n)
(do ((i n (- i 1))
(result lst (cdr result)))
((or (null? result)
(zero? i))
result)))
(define make-circular-list
(let ((documentation "(make-circular-list n init) returns a circular list with n entries initialized to init:\n\
(make-circular-list 3 #f) -> #1=(#f #f #f . #1#)"))
(lambda* (n init)
(let ((lst (make-list n init)))
(set-cdr! (list-tail lst (- n 1)) lst)))))
(define circular-list
(let ((documentation "(circular-list . objs) returns a circular list with objs:\n\
(circular-list 1 2) -> #1=(1 2 . #1#)"))
(lambda objs
(let ((lst (copy objs)))
(set-cdr! (list-tail lst (- (length lst) 1)) lst)))))
(define circular-list?
(let ((documentation "(circular-list? obj) returns #t if obj is a circular list"))
(lambda (obj)
(catch #t
(lambda () (infinite? (length obj)))
(lambda args #f)))))
(define linearize
(let ((documentation " (linearize lst) turns a circular list into normal list:\n\
(linearize (circular-list 1 2)) -> '(1 2)"))
(lambda (lst)
(let lin-1 ((lst lst)
(result ())
(sofar ()))
(if (or (not (pair? lst)) (memq lst sofar))
(reverse! result)
(lin-1 (cdr lst) (cons (car lst) result) (cons lst sofar)))))))
(define cyclic?
(let ((documentation "(cyclic obj) returns #t if the sequence obj contains any cycles"))
(lambda (obj)
(pair? (cyclic-sequences obj)))))
(define copy-tree
(let ((documentation "(copy-tree lst) returns a full copy of lst"))
(lambda (lis)
(if (pair? lis)
(cons (copy-tree (car lis))
(copy-tree (cdr lis)))
lis))))
(define tree-member
(let ((documentation "(tree-member sym tree) returns #t if sym is found anywhere in tree:\n\
(tree-member 'a '(1 (2 a))) -> #t"))
(lambda (sym tree)
(and (pair? tree)
(or (eq? (car tree) sym)
(and (pair? (car tree))
(tree-member sym (car tree)))
(tree-member sym (cdr tree)))))))
(define adjoin
(let ((documentation "(adjoin obj lst) adds obj to lst if it is not already in lst, returning the new list"))
(lambda (obj lst)
(if (member obj lst) lst (cons obj lst)))))
(define (cdr-assoc obj lst)
(cond ((assoc obj lst) => cdr)
(else #f)))
;;; this used to be built into s7.c, but no one uses it.
(define-macro (multiple-value-set! vars expr . body)
(if (pair? vars)
(let ((local-vars (map (lambda (n) (gensym)) vars)))
`((lambda ,local-vars
,@(map (lambda (n ln) `(set! ,n ,ln)) vars local-vars)
,@body)
,expr))
(if (and (null? vars) (null? expr))
(cons 'begin body)
(error 'syntax-error "multiple-value-set! vars/exprs messed up"))))
;;; ----------------
(define-macro (fully-macroexpand form)
(list 'quote
(let expand ((form form))
(cond ((not (pair? form)) form)
((and (symbol? (car form))
(macro? (symbol->value (car form))))
(expand (apply macroexpand (list form))))
((and (eq? (car form) 'set!) ; look for (set! (mac ...) ...) and use mac's procedure-setter
(pair? (cdr form))
(pair? (cadr form))
(macro? (symbol->value (caadr form))))
(expand (apply (eval (procedure-source (procedure-setter (symbol->value (caadr form)))))
(append (cdadr form) (cddr form)))))
(else (cons (expand (car form))
(expand (cdr form))))))))
(define-macro (define-with-macros name&args . body)
`(apply define ',name&args (list (fully-macroexpand `(begin ,,@body)))))
(define setf
(let ((args (gensym))
(name (gensym)))
(apply define-bacro `((,name . ,args)
(unless (null? ,args)
(apply set! (car ,args) (cadr ,args) ())
(apply setf (cddr ,args)))))))
(define-macro* (incf sym (inc 1))
`(set! ,sym (+ ,sym ,inc))) ; or (list-values set! sym (list-values + sym inc))
;; (define-bacro* (incf-1 sym (inc 1)) (apply set! sym (list + sym inc) ()))
(define-macro* (decf sym (dec 1))
`(set! ,sym (- ,sym ,dec)))
(define-macro (shiftf . places)
(let ((tmp (gensym)))
`(let ((,tmp ,(car places)))
,@(map (lambda (a b)
`(set! ,a ,b))
places
(cdr places))
,tmp)))
(define-macro (rotatef . places)
(let ((tmp (gensym))
(last (places (- (length places) 1))))
`(let ((,tmp ,(car places)))
,@(map (lambda (a b)
`(set! ,a ,b))
places
(cdr places))
(set! ,last ,tmp))))
(define-macro (progv vars vals . body)
`(apply (apply lambda ,vars ',body) ,vals))
(define-macro (symbol-set! var val) ; like CL's set
`(apply set! ,var ',val ()))
(define-macro (value->symbol expr)
`(let ((val ,expr)
(e1 (curlet)))
(call-with-exit
(lambda (return)
(do ((e e1 (outlet e))) ()
(for-each
(lambda (slot)
(if (equal? val (cdr slot))
(return (car slot))))
e)
(if (eq? e (rootlet))
(return #f)))))))
(define-macro (enum . args)
`(for-each define ',args (iota (length ',args))))
(define-macro (destructuring-bind lst expr . body) ; if only there were some use for this!
(cons 'let
(cons (let flatten ((lst1 lst)
(lst2 (eval expr))
(args ()))
(cond ((null? lst1) args)
((not (pair? lst1)) (cons (list lst1 lst2) args))
(else (flatten (car lst1) (car lst2)
(flatten (cdr lst1) (cdr lst2) args)))))
body)))
#|
;; kinda ugly!
(define-macro (and-map func args)
`(let and-map-loop ((args ,args))
(or (null? args)
(and (eval (list ,func (car args)))
(and-map-loop (cdr args))))))
|#
(define-macro (and-let* vars . body) ; bind vars, if any is #f stop, else evaluate body with those bindings
`(let () (and ,@(map (lambda (v) `(define ,@v)) vars) (begin ,@body))))
(define-macro (let*-temporarily vars . body)
`(with-let (#_inlet :orig (#_curlet)
:saved (#_list ,@(map car vars)))
(dynamic-wind
(lambda () #f)
(lambda ()
(with-let orig
,@(map (lambda (v)
`(set! ,(car v) ,(cadr v)))
vars)
,@body))
(lambda ()
,@(map (let ((ctr -1))
(lambda (v)
(if (symbol? (car v))
`(set! (orig ',(car v)) (list-ref saved ,(set! ctr (+ ctr 1))))
`(set! (with-let orig ,(car v)) (list-ref saved ,(set! ctr (+ ctr 1)))))))
vars)))))
;;; 14-8-16: moved let-temporarily to s7.c
(define-macro (while test . body) ; while loop with predefined break and continue
`(call-with-exit
(lambda (break)
(let continue ()
(if (let () ,test)
(begin
(let () ,@body)
(continue))
(break))))))
(define-macro (do* spec end . body)
`(let* ,(map (lambda (var)
(list (car var) (cadr var)))
spec)
(do () ,end
,@body
,@(map (lambda (var)
(if (pair? (cddr var))
`(set! ,(car var) ,(caddr var))
(values)))
spec))))
(define-macro (string-case selector . clauses)
(cons 'case ; case with string constant keys
(cons (list 'symbol selector)
(map (lambda (clause)
(if (pair? (car clause))
(cons (map symbol (car clause)) (cdr clause))
clause))
clauses))))
(define-macro (eval-case key . clauses) ; case with evaluated key-lists
(let ((select (gensym)))
`(let ((,select ,key))
(cond ,@(map (lambda (lst)
(if (not (pair? (car lst)))
lst
(cons `(member ,select (list ,@(car lst)))
(cdr lst))))
clauses)))))
;;; ----------------
(define hash-table->alist
(let ((documentation "(hash-table->alist table) returns the contents of table as an association list:\n\
(hash-table->alist (hash-table '(a . 1))) -> '((a . 1))"))
(lambda (table)
(if (hash-table? table)
(map values table)
(error 'wrong-type-arg "hash-table->alist argument, ~A, is not a hash-table" table)))))
(define merge-hash-tables
(let ((documentation "(merge-hash-tables . tables) returns a new hash-table with the contents of all the tables"))
(lambda tables
(apply hash-table
(apply append
(map hash-table->alist tables))))))
;;; ----------------
(define-macro (c?r path)
(define (X-marks-the-spot accessor tree)
(if (pair? tree)
(or (X-marks-the-spot (cons 'car accessor) (car tree))
(X-marks-the-spot (cons 'cdr accessor) (cdr tree)))
(and (eq? tree 'X) accessor)))
(let ((body 'lst))
(for-each
(lambda (f)
(set! body (list f body)))
(reverse (X-marks-the-spot () path)))
`(dilambda
(lambda (lst)
,body)
(lambda (lst val)
(set! ,body val)))))
;;; ----------------
(define find-if
(let ((documentation "(find-if func sequence) applies func to each member of sequence.\n\
If func approves of one, find-if returns that member of the sequence"))
(lambda (f sequence)
(call-with-exit
(lambda (return)
(for-each (lambda (arg)
(if (f arg)
(return arg)))
sequence)
#f)))))
(define member?
(let ((documentation "(member? obj sequence) returns #t if obj is an element of sequence"))
(lambda (obj sequence)
(find-if (lambda (x) (equal? x obj)) sequence))))
(define index-if
(let ((documentation "(index-if func sequence) applies func to each member of sequence.\n\
If func approves of one, index-if returns the index that gives that element's position.\n\
(index-if (lambda (x) (= x 32)) #(0 1 32 4)) -> 2\n\
(index-if (lambda (x) (= (cdr x) 32)) (hash-table '(a . 1) '(b . 32))) -> 'b"))
(lambda (f sequence)
(call-with-exit
(lambda (return)
(if (or (hash-table? sequence)
(let? sequence))
(for-each (lambda (arg)
(if (f arg) (return (car arg))))
sequence)
(let ((position 0))
(for-each (lambda (arg)
(if (f arg) (return position))
(set! position (+ position 1)))
sequence)))
#f)))))
(define count-if
(let ((documentation "(count-if func sequence) applies func to each member of sequence, returning the number of times func approves."))
(lambda (f sequence)
(let ((count 0))
(for-each (lambda (arg)
(if (f arg)
(set! count (+ count 1))))
sequence)
count))))
(define every?
(let ((documentation "(every? func sequence) returns #t if func approves of every member of sequence"))
(lambda (f sequence)
(call-with-exit
(lambda (return)
(for-each (lambda (arg) (if (not (f arg)) (return #f))) sequence)
#t)))))
(define any?
(let ((documentation "(any? func sequence) returns #t if func approves of any member of sequence"))
(lambda (f sequence)
(call-with-exit
(lambda (return)
(for-each (lambda (arg) (if (f arg) (return #t))) sequence)
#f)))))
(define collect-if
(let ((documentation "(collect-if type func sequence) gathers the elements of sequence that satisfy func, and returns them via type:\n\
(collect-if list integer? #(1.4 2/3 1 1+i 2)) -> '(1 2)"))
(lambda (type f sequence)
(apply type (map (lambda (arg) (if (f arg) arg (values))) sequence)))))
;;; if type=list, this is slightly wasteful because list currently copies its args, so:
;;; ((if (eq? type list) values (values apply type)) ...) would work
;;;
;;; to return (f arg) rather than arg, (apply type (map f sequence))
(define remove-if
(let ((documentation "(remove-if type f sequence) returns via type the elements of sequence that do not satisfy func:\n\
(remove-if list integer? #(1.4 2/3 1 1+i 2)) -> '(1.4 2/3 1+1i)"))
(lambda (type f sequence)
(collect-if type (lambda (obj) (not (f obj))) sequence))))
(define nonce
(let ((documentation "(nonce type sequence) returns via type the elements of sequence that occur only once"))
(lambda (type sequence)
(collect-if type (lambda (obj) (= (count-if (lambda (x) (equal? x obj)) sequence) 1)) sequence))))
(define full-find-if
(let ((documentation "(full-find-if func sequence) searches sequence, and recursively any sequences it contains, for an element that satisfies func"))
(lambda (f sequence)
(if (and (procedure? f)
(aritable? f 1))
(if (sequence? sequence)
(call-with-exit
(lambda (return)
(let full-find-if-1 ((seq sequence))
(for-each
(lambda (x)
(if (f x)
(return x)
(if (sequence? x) (full-find-if-1 x))))
seq))
#f))
(error 'wrong-type-arg "full-find-if second argument, ~A, is not a sequence" sequence))
(error 'wrong-type-arg "full-find-if first argument, ~A, is not a procedure of one argument" f)))))
(define full-count-if
(let ((documentation "(full-count-if func sequence) searches sequence, and recursively any sequences it contains, returning the number of elements that satisfy func"))
(lambda (f sequence)
(let ((count 0))
(full-find-if (lambda (x) (if (f x) (set! count (+ count 1))) #f) sequence)
count))))
(define full-index-if
(let ((documentation "(full-index-if func sequence) searches sequence, and recursively any sequences it contains, returning the indices of the first element that satisfies func:\n\
(full-index-if (lambda (x) (and (integer? x) (= x 3))) '(1 (2 3))) -> '(1 1)"))
(lambda (f sequence)
(call-with-exit
(lambda (return)
(letrec ((full-index-if-1
(lambda (f seq path)
(if (or (hash-table? seq)
(let? seq))
(for-each (lambda (arg)
(if (f arg)
(return (reverse (cons (car arg) path)))
(if (indexable? (cdr arg))
(full-index-if-1 f (cdr arg) (cons (car arg) path)))))
seq)
(let ((position 0))
(for-each (lambda (arg)
(if (f arg)
(return (reverse (cons position path)))
(if (indexable? arg)
(full-index-if-1 f arg (cons position path))))
(set! position (+ position 1)))
seq))))))
(full-index-if-1 f sequence ())
#f))))))
(define (make-complete-iterator obj)
(let ((iters ())
(cycles (cyclic-sequences obj))
(seen-cycles ()))
(define (make-careful-iterator p)
(if (not (pair? p))
(make-iterator p)
(let ((len (length p)))
(make-iterator
(cond ((infinite? len) ; circular list
(let ((cur p)
(iterator? #t))
(lambda ()
(if (memq cur seen-cycles)
#<eof>
(let ((result (car cur)))
(if (memq cur cycles)
(set! seen-cycles (cons cur seen-cycles)))
(set! cur (cdr cur))
result)))))
((positive? len) ; normal list
p)
(else
(let ((cur p) ; dotted list
(iterator? #t))
(lambda ()
(if (pair? cur)
(let ((result (car cur)))
(set! cur (cdr cur))
result)
(let ((result cur))
(set! cur #<eof>)
result))))))))))
(make-iterator
(let ((iter (make-careful-iterator obj))
(iterator? #t))
(define (iterloop) ; define returns the new value
(define (iter-memq p q)
(and (pair? q)
(or (eq? p (iterator-sequence (car q)))
(iter-memq p (cdr q)))))
(let ((result (iter)))
(cond ((length result)
(if (or (memq result seen-cycles) ; we've dealt with it already, so skip it
(eq? result (iterator-sequence iter))
(iter-memq result iters)) ; we're dealing with it the right now
(iterloop) ; this means the outermost sequence is ignored if encountered during the traversal
(begin
(set! iters (cons iter iters))
(set! iter (make-careful-iterator result))
result)))
((not (eq? result #<eof>))
result)
((null? iters)
#<eof>)
(else
(set! seen-cycles (cons (iterator-sequence iter) seen-cycles))
(set! iter (car iters))
(set! iters (cdr iters))
(iterloop)))))))))
(define safe-find-if
(let ((documentation "(safe-find-if func sequence) searches sequence, and recursively any sequences it contains, for an element that satisfies func.\
Unlike full-find-if, safe-find-if can handle any circularity in the sequences."))
(lambda (f sequence)
(let ((iter (make-complete-iterator sequence)))
(let loop ((x (iter)))
(if (f x) x
(and (not (and (eq? x #<eof>)
(iterator-at-end? iter)))
(loop (iter)))))))))
(define (safe-count-if f sequence)
;; currently the complete-iterator above skips repetitions, including the outer sequence,
;; so this count will be off if there are repeated cycles?
;; Perhaps make an iterator that returns everything.
(if (sequence? sequence)
(if (procedure? f)
(let ((count 0))
(safe-find-if (lambda (x) (if (f x) (set! count (+ count 1))) #f) sequence)
count)
(error 'wrong-type-arg "safe-count-if first argument, ~A, should be a function" f))
(error 'wrong-type-arg "safe-count-if second argument, ~A, should be a sequence" sequence)))
;;; ----------------
(define sequences->list
(let ((documentation "(sequences->list . sequences) returns a list of elements of all the sequences:\n\
(sequences->list \"hi\" #(0 1) (hash-table '(a . 2))) -> '(#\\h #\\i 0 1 (a . 2))"))
(lambda sequences
(apply append
(map (lambda (sequence)
(map values sequence))
sequences)))))
(define concatenate
(let ((documentation "(concatenate type . sequences) concatenates sequences returning an object of type:\n\
(concatenate vector '(1 2) #(3 4)) -> #(1 2 3 4)"))
(lambda (type . sequences)
(apply type (apply sequences->list sequences)))))
(define intersection
(let ((documentation "(intersection type . sequences) returns via type the intersection of the sequences:\n\
(intersection vector '(1 2 3) #(2 3 4)) -> #(2 3)"))
(lambda (type . sequences)
(if (every? sequence? sequences)
(apply type (let ((lst ()))
(if (pair? sequences)
(for-each (lambda (obj)
(if (every? (lambda (seq)
(member? obj seq))
(cdr sequences))
(set! lst (cons obj lst))))
(car sequences)))
(reverse lst)))
(error 'wrong-type-arg "intersection arguments should be sequences: ~A" sequences)))))
(define union
(let ((documentation "(union type . sequences) returns via type the union of the sequences:\n\
(union vector '(1 2 3) #(2 3 4)) -> #(1 2 3 4)"))
(lambda (type . sequences)
(apply type (let ((lst ()))
(for-each (lambda (obj)
(if (not (member obj lst))
(set! lst (cons obj lst))))
(apply sequences->list sequences))
(reverse lst))))))
(define asymmetric-difference
(let ((documentation "(asymmetric-difference type . sequences) returns the elements in the rest of the sequences that are not in the first:\n\
(asymmetric-difference vector '(1 2 3) #(2 3 4) '(1 5)) -> #(4 5)"))
(lambda (type . sequences) ; complement, elements in B's not in A
(if (not (and (pair? sequences)
(pair? (cdr sequences))))
(type)
(collect-if type (lambda (obj)
(not (member obj (car sequences))))
(apply union list (cdr sequences)))))))
(define cl-set-difference
(let ((documentation "(cl-set-difference type .sequences) returns the elements in the first sequence that are not in the rest of the sequences:\n\
(cl-set-difference vector '(1 2 3) #(2 3 4) '(1 5)) -> #()"))
(lambda (type . sequences) ; CL: elements in A not in B's
(if (not (and (pair? sequences)
(pair? (cdr sequences))))
(type)
(let ((others (apply union list (cdr sequences))))
(collect-if type (lambda (obj)
(not (member obj others)))
(car sequences)))))))
(define symmetric-difference
(let ((documentation "(symmetric-difference type .sequences) returns the elements that are in an odd number of the sequences:\n\
(symmetric-difference vector '(1 2 3) #(2 3 4) '(5)) -> #(1 4 5)"))
(lambda (type . sequences) ; xor, elements in an odd number of sequences (logxor A B...)
(let ((all (apply sequences->list sequences)))
(collect-if type (lambda (obj)
(odd? (count-if (lambda (x)
(equal? x obj))
all)))
(apply union list sequences))))))
(define power-set
(let ((documentation "(power-set type . sequences) returns the power set of the union of the elements in the sequences."))
(lambda (type . sequences) ; ignoring repeats
(apply type
(let pset ((set (apply union list sequences)))
(if (null? set)
'(())
(let ((rest (pset (cdr set))))
(append rest (map (lambda (subset) (cons (car set) subset)) rest)))))))))
;;; ----------------
(define ->predicate
(let ((predicates (list integer? rational? real? complex? number?
byte-vector? string?
float-vector? int-vector? vector?
null? proper-list? pair? list?
keyword? gensym? symbol?
char? string?
hash-table?
iterator?
continuation?
input-port? output-port?
let?
dilambda? procedure? macro?
boolean?
random-state?
eof-object?
c-object?
c-pointer?
(lambda (obj)
(eq? obj #<unspecified>))
(lambda (obj)
(eq? obj #<undefined>))
(lambda (obj)
(memq obj (list quote if when unless begin set! let let* letrec letrec* cond and or case do
lambda lambda* define define* define-macro define-macro* define-bacro define-bacro*
define-constant with-baffle macroexpand with-let)))))
(documentation "(->predicate obj) returns the type predicate function for obj: (->predicate 31) -> integer?"))
(lambda (obj)
(find-if (lambda (pred) (pred obj)) predicates))))
(define add-predicate
(let ((documentation "(add-predicate p) adds p (a boolean function of one argument) to the list of predicates used by ->predicate"))
(lambda (p)
(if (and (procedure? p)
(aritable? p 1))
(let ((e (funclet ->predicate)))
(set! (e 'predicates) (cons p (e 'predicates))))
(error 'wrong-type-arg "add-predicate argument, ~A, is not a procedure of one argument" p)))))
(define typeq?
(let ((documentation "(typeq? . objs) returns #t if all objs have the same type (as determined by ->predicate)"))
(lambda objs
(or (null? objs)
(every? (->predicate (car objs)) (cdr objs))))))
(define-macro (typecase expr . clauses) ; actually type=any boolean func
(let ((obj (gensym)))
`(begin ; normally this would be (let ((,obj ,expr)) ...)
(define ,obj ,expr) ; but use begin so that internal defines are not blocked
(cond ,@(map (lambda (clause)
(if (memq (car clause) '(#t else))
clause
(if (= (length (car clause)) 1)
(cons (list (caar clause) obj) (cdr clause))
(cons (cons 'or (map (lambda (type)
(list type obj))
(car clause)))
(cdr clause)))))
clauses)))))
;;; ----------------
(define 2^n?
(let ((documentation "(2^n? x) returns #t if x is a power of 2"))
(lambda (x)
(and (integer> x)
(not (zero? x))
(zero? (logand x (- x 1)))))))
(define (2^n-1? x)
(and (integer? x)
(zero? (logand x (+ x 1)))))
(define (lognand . ints)
(lognot (apply logand ints)))
(define (lognor . ints)
(lognot (apply logior ints)))
(define (logeqv . ints)
(lognot (apply logxor (if (odd? (length ints))
(values -1 ints) ; Clisp does it this way
ints))))
(define (log-none-of . ints) ; bits on in none of ints
(lognot (apply logior ints)))
(define log-all-of logand) ; bits on in all of ints
(define log-any-of logior) ; bits on in at least 1 of ints
(define (log-n-of n . ints) ; return the bits on in exactly n of ints
(if (not (integer? n))
(error 'wrong-type-arg "log-n-of first argument, ~A, should be an integer" n)
(if (not (every? integer? ints))
(error 'wrong-type-arg "log-n-of ints arguments, ~A, should all be integers" ints)
(let ((len (length ints)))
(cond ((= len 0) (if (= n 0) -1 0))
((= n 0) (lognot (apply logior ints)))
((= n len) (apply logand ints))
((> n len) 0)
(#t
(do ((1s 0)
(prev ints)
(nxt (cdr ints))
(ln (- len 1))
(nn (- n 1))
(i 0 (+ i 1)))
((= i len) 1s)
(let ((cur (ints i)))
(if (= i 0)
(set! 1s (logior 1s (logand cur (apply log-n-of nn nxt))))
(let ((mid (cdr prev)))
(set! (cdr prev) (if (= i ln) () (cdr mid)))
(set! 1s (logior 1s (logand cur (apply log-n-of nn ints))))
(set! (cdr prev) mid)
(set! prev mid)))))))))))
;; from Rick
(define (byte siz pos) ;; -> cache size, position and mask.
(list siz pos (ash (- (ash 1 siz) 1) pos)))
(define byte-size car)
(define byte-position cadr)
(define byte-mask caddr)
(define (ldb bytespec integer)
(ash (logand integer (byte-mask bytespec))
(- (byte-position bytespec))))
(define (dpb integer bytespec into)
(logior (ash (logand integer (- (ash 1 (byte-size bytespec)) 1)) (byte-position bytespec))
(logand into (lognot (byte-mask bytespec)))))
;;; ----------------
(define-macro* (define-class class-name inherited-classes (slots ()) (methods ()))
`(let ((outer-env (outlet (curlet)))
(new-methods ())
(new-slots ()))
(for-each
(lambda (class)
;; each class is a set of nested environments, the innermost (first in the list)
;; holds the local slots which are copied each time an instance is created,
;; the next holds the class slots (global to all instances, not copied);
;; these hold the class name and other such info. The remaining environments
;; hold the methods, with the localmost method first. So in this loop, we
;; are gathering the local slots and all the methods of the inherited
;; classes, and will splice them together below as a new class.
(set! new-slots (append (let->list class) new-slots))
(do ((e (outlet (outlet class)) (outlet e)))
((or (not (let? e))
(eq? e (rootlet))))
(set! new-methods (append (let->list e) new-methods))))
,inherited-classes)
(let ((remove-duplicates
(lambda (lst) ; if multiple local slots with same name, take the localmost
(letrec ((rem-dup
(lambda (lst nlst)
(cond ((null? lst) nlst)
((assq (caar lst) nlst) (rem-dup (cdr lst) nlst))
(else (rem-dup (cdr lst) (cons (car lst) nlst)))))))
(reverse (rem-dup lst ()))))))
(set! new-slots
(remove-duplicates
(append (map (lambda (slot)
(if (pair? slot)
(cons (car slot) (cadr slot))
(cons slot #f)))
,slots) ; the incoming new slots, #f is the default value
new-slots)))) ; the inherited slots
(set! new-methods
(append (map (lambda (method)
(if (pair? method)
(cons (car method) (cadr method))
(cons method #f)))
,methods) ; the incoming new methods
;; add an object->string method for this class (this is already a generic function).
(list (cons 'object->string
(lambda* (obj (use-write #t))
(if (eq? use-write :readable) ; write readably
(format #f "(make-~A~{ :~A ~W~^~})"
',class-name
(map (lambda (slot)
(values (car slot) (cdr slot)))
obj))
(format #f "#<~A: ~{~A~^ ~}>"
',class-name
(map (lambda (slot)
(list (car slot) (cdr slot)))
obj))))))
(reverse! new-methods))) ; the inherited methods, shadowed automatically
(let ((new-class (openlet
(apply sublet ; the local slots
(sublet ; the global slots
(apply inlet ; the methods
(reverse new-methods))
'class-name ',class-name ; class-name slot
'inherited ,inherited-classes
'inheritors ()) ; classes that inherit from this class
new-slots))))
(varlet outer-env
',class-name new-class ; define the class as class-name in the calling environment
;; define class-name? type check
(string->symbol (string-append (symbol->string ',class-name) "?"))
(lambda (obj)
(and (let? obj)
(eq? (obj 'class-name) ',class-name))))
(varlet outer-env
;; define the make-instance function for this class.
;; Each slot is a keyword argument to the make function.
(string->symbol (string-append "make-" (symbol->string ',class-name)))
(apply lambda* (map (lambda (slot)
(if (pair? slot)
(list (car slot) (cdr slot))
(list slot #f)))
new-slots)
`((let ((new-obj (copy ,,class-name)))
,@(map (lambda (slot)
`(set! (new-obj ',(car slot)) ,(car slot)))
new-slots)
new-obj))))
;; save inheritance info for this class for subsequent define-method
(letrec ((add-inheritor (lambda (class)
(for-each add-inheritor (class 'inherited))
(if (not (memq new-class (class 'inheritors)))
(set! (class 'inheritors) (cons new-class (class 'inheritors)))))))
(for-each add-inheritor ,inherited-classes))
',class-name)))
(define-macro (define-generic name) ; (define (genfun any) ((any 'genfun) any))
`(define ,name
(lambda args
(let ((gf ((car args) ',name))) ; get local definition
(if (not (eq? gf ,name)) ; avoid infinite recursion
(apply gf args)
(error 'syntax-error "attempt to call generic function wrapper recursively"))))))
(define-macro (define-slot-accessor name slot)
`(define ,name (dilambda
(lambda (obj) (obj ',slot))
(lambda (obj val) (set! (obj ',slot) val)))))
(define-macro (define-method name-and-args . body)
`(let* ((outer-env (outlet (curlet)))
(method-name (car ',name-and-args))
(method-args (cdr ',name-and-args))
(object (caar method-args))
(class (symbol->value (cadar method-args)))
(old-method (class method-name))
(method (apply lambda* method-args ',body)))
;; define the method as a normal-looking function