-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmt-utils.lisp
1592 lines (1321 loc) · 48.7 KB
/
mt-utils.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
(in-package :mt)
#| ######################################################################
Random Lisp utilities
Copyright (c) 1994-2010 Michael Travers
Permission is given to use and modify this code as long
as the copyright notice is preserved.
Send questions, comments, and fixes to [email protected].
-------------------------------------------------------------------------
This file contains a large miscellany of useful hacks that I have come
to depend on.
Originally written for MCL; this library now has been used with SBCL,
ACL, and ABCL as well.
Many items here are borrowed from others. In most cases the source
is acknowledged.
NOTE: This is the canonical version! Accept no substitutes.
###################################################################### |#
;;; Generalized variables, lists, binding, etc.
(defmacro deletef (thing place &rest delete-args)
`(setf ,place (delete ,thing ,place ,@delete-args)))
(defmacro removef (thing place &rest remove-args)
`(setf ,place (remove ,thing ,place ,@remove-args)))
;;; Like push, but will remove an existing element if its already there. A typical use
;;; is managing lists of tagged structures. KEY is applied to THING as well as to the elements
;;; of PLACE, and in fact this operation only makes sense with a KEY arg.
;;; should have once-only +++
(defmacro replacef (thing place &rest delete-args &key (key #'identity) &allow-other-keys)
`(progn
(deletef (funcall ,key ,thing) ,place ,@delete-args)
(push ,thing ,place)))
(defmacro push-end (thing place)
`(setf ,place
(nconc ,place
(list ,thing))))
(defmacro pop-end (place)
`(let* ((last (last ,place 2))
(v (cadr last)))
(if (null (cdr last))
(pop ,place)
(progn
(rplacd last nil)
v))))
(defmacro pushnew-end (item place &key (test #'eql))
`(if (member ,item ,place :test ,test)
,place
(push-end ,item ,place)))
(defun list-insert (list item n)
(assert (> n 0)) ; unpleasant otherwise
(let ((cdr (nthcdr (1- n) list)))
(rplacd cdr (cons item (cdr cdr)))
list))
; destructive
(defun insert-before (list new before)
(if (null before)
(nconc list (list new))
(do ((rest list (cdr rest))
(last nil rest))
((null rest)
(error "insert-before: ~A not in ~A" before list))
(if (eq before (car rest))
(if last
(progn (rplacd last (cons new rest))
(return list))
(return (cons new list)))))))
(defun firstn (list n)
(if (>= n (length list))
list
(subseq list 0 n)))
;;; Could be even safer I suppose
(defun subseq-safe (list from &optional to)
(subseq list from (and to (min to (length list)))))
(defun break-list (l n)
"Break LIST into sublists of length N"
(if l
(cons (firstn l n)
(break-list (nthcdr n l) n))))
;;; If the lists are not sets (have duplicated items) result is undefined
(defun set-equal (l1 l2 &key (test #'eq))
(and (= (length l1) (length l2))
(dolist (elt l1 t)
(unless (find elt l2 :test test)
(return nil)))))
(defun stable-nset-difference (list1 list2 &key (test #'eql))
#.(doc
"Like NSET-DIFFERENCE, but preserves the order of the LIST1 argument")
(do ((rest list1 (cdr rest))
(prev nil rest)
(head nil)
(splice-to nil))
((endp rest)
(when splice-to
(rplacd splice-to nil))
head)
(if (member (car rest) list2 :test test)
(progn
(unless splice-to
(setf splice-to prev)))
(progn
(when (null head)
(setf head rest))
(when splice-to
(rplacd splice-to rest)
(setf splice-to nil))))))
(defun listify (thing)
(if (listp thing)
thing
(list thing)))
(defun unlistify (thing)
(if (and (consp thing)
(null (cdr thing))) ;(= 1 (length thing)), but faster
(first thing)
thing))
;;; for descending down alist type structures, esp. those in JSON-like form
(defun findprop (prop structure)
(cadr (member prop structure :test #'equal)))
;;; recursive version of above
(defun findprops (structure &rest props)
(if (null props)
structure
(apply #'findprops (findprop structure (car props)) (cdr props))))
;;; From BioLisp
(defmacro assocadr (key alist &rest assoc-keywords)
"Shorthand for (CADR (ASSOC ...))"
`(cadr (assoc ,key ,alist ,@assoc-keywords)))
(defmacro assocdr (key alist &rest assoc-keywords)
"Shorthand for (CDR (ASSOC ...))"
`(cdr (assoc ,key ,alist ,@assoc-keywords)))
;;; mv-let*: lets the car of a let binding form be a list
;;; elements of which get bound to multiple values.
(defmacro mv-let* (forms &body body)
(cond ((null forms)
`(progn ,@body))
((or (symbolp (car forms))
(symbolp (caar forms)))
`(let (,(car forms))
(mv-let* ,(cdr forms)
,@body)))
(t
`(multiple-value-bind ,(caar forms) ,(cadar forms)
(mv-let* ,(cdr forms)
,@body)))))
;;; Lifted from PCL. Ensure that a macro variable is only expanded once.
(defmacro once-only (vars &body body)
(let ((gensym-var (gensym))
(run-time-vars (gensym))
(run-time-vals (gensym))
(expand-time-val-forms ()))
(dolist (var vars)
(push `(if (or (symbolp ,var)
(numberp ,var)
(and (listp ,var)
(member (car ,var) '(quote function))))
,var
(let ((,gensym-var (gensym)))
(push ,gensym-var ,run-time-vars)
(push ,var ,run-time-vals)
,gensym-var))
expand-time-val-forms))
`(let* (,run-time-vars
,run-time-vals
(wrapped-body
((lambda ,vars . ,body) . ,(reverse expand-time-val-forms))))
`((lambda ,(nreverse ,run-time-vars) ,wrapped-body)
. ,(nreverse ,run-time-vals)))))
#-CCL
(defmacro let-globally (clauses &body body)
(let ((temp-vars (mapcar #'(lambda (s) (gensym (symbol-name (car s)))) clauses)))
`(let ,(mapcar #'(lambda (temp clause) `(,temp ,(car clause))) temp-vars clauses)
(unwind-protect
(progn
,@(mapcar #'(lambda (clause)
(cons 'setf clause))
clauses)
,@body)
,@(mapcar #'(lambda (temp clause)
`(setf ,(car clause) ,temp))
temp-vars clauses)))))
;;; destructuring-let
;;; Random small aids to expression
(defmacro non-nil (var)
`(and (boundp ',var)
,var))
#-:SBCL
(declaim (ignore ignore)) ; So sue me
(defmacro return-if (val)
(once-only (val)
`(if ,val (return ,val))))
(defmacro return-from-if (block val)
(once-only (val)
`(if ,val (return-from ,block ,val))))
#-CCL ; CCL has this built in
(defmacro neq (a b)
`(not (eq ,a ,b)))
(defun circular-list (&rest elements)
(rplacd (last elements) elements))
(defun fringe (list)
(cond ((null list) nil)
((listp list)
(append (fringe (car list)) (fringe (cdr list))))
(t (list list))))
;;; Collecting and relatives
(defmacro collecting (&body body)
`(let ((%results nil))
(flet ((collect (thing) (push thing %results))
(collect-if (thing) (when thing (push thing %results)))
(collect-new (thing &optional (test #'eql)) (pushnew thing %results :test test))
(collect-all (things) (setf %results (append things %results))))
(declare (ignorable (function collect) (function collect-if) (function collect-new)))
,@body)
(nreverse %results)))
(defmacro summing (&body body)
`(let ((%result 0))
(flet ((sum (thing) (incf %result thing)))
,@body)
%result))
(defmacro accumulating (init func &body body)
`(let ((%result ,init))
(flet ((accumulate (thing)
(setf %result (funcall ,func %result thing))))
,@body)
%result))
;;; Iteration and Mapping
;;; Like dolist, but works with any sequence
(defmacro dosequence ((var sequence &optional result) &body body)
(let ((index (gensym))
(len (gensym)))
`(do ((,index 0 (1+ ,index))
(,len (length ,sequence))
,var)
((= ,index ,len)
,result)
(setq ,var (elt ,sequence ,index))
,@body)))
(defun mapsequence (proc sequence)
(collecting
(dosequence (v sequence)
(collect (funcall proc v)))))
(defun last-elt (seq)
(elt seq (1- (length seq))))
(defmacro do-for-array-elements (array vars &body body)
`(let ((array-dimensions (array-dimensions ,array)))
(do-for-array-elements-1 ,array ,vars 0 ,@body)))
(defmacro do-for-array-elements-1 (array vars dim &body body)
(if vars
`(dotimes (,(car vars) (nth ,dim array-dimensions))
(do-for-array-elements-1 ,array ,(cdr vars) ,(1+ dim)
,@body))
`(progn ,@body)))
;;; generalized good iterator.
;;; Maximum/minimums
;;; +++ flush return-max, use multiple values instead
(defun extreme (list test &key (key #'identity) (return-max nil))
(and list
(let* ((best (car list))
(max (funcall key best)))
(dolist (other (cdr list) (if return-max max best))
(let ((score (funcall key other)))
(when (funcall test score max)
(setq best other max score)))))))
; +++ key arguments are slow
(defun extremes (list test &key (key #'identity))
(if list
(let* ((best (list (car list)))
(max (funcall key (car best))))
(dolist (other (cdr list) (values best max))
(let ((score (funcall key other)))
(if (funcall test score max)
(setq best (list other) max score)
(if (funcall test max score)
nil
(push other best))))))
(values nil most-negative-fixnum)))
(defun maximize (list &key (key #'identity) (return-max nil))
(declare (inline extreme)) ; not that this does anything
(extreme list #'> :key key :return-max return-max))
(defun minimize (list &key (key #'identity) (return-max nil))
(declare (inline extreme)) ; not that this does anything
(extreme list #'< :key key :return-max return-max))
(defun maximums (list &key (key #'identity))
(declare (inline extremes)) ; not that this does anything
(extremes list #'> :key key))
(defun minimums (list &key (key #'identity))
(declare (inline extremes)) ; not that this does anything
(extremes list #'< :key key))
(defun closest (value list key)
(minimize list :key #'(lambda (elt) (abs (- value (funcall key elt))))))
;;; Various mapping functions
;;; Most of these borrowed from Ken Haase
#-ABCL ;;; has a collect fn built in, need to change name
(defun collect (fcn list)
"Applies FCN to each element of LIST returning all the non-nil values as a list."
(let* ((head (list 'HEAD))
(tail head))
(dolist (elt list (cdr head))
(let ((value (funcall fcn elt)))
(when value
(push value (cdr tail))
(setf tail (cdr tail)))))))
(defun mapappend (fcn list)
"Applies FCN to every element of LIST, appending the results together.
Order is maintained as one might expect."
(let* ((head (list '())) (tail head))
(dolist (elt list (cdr head))
(dolist (result-elt (funcall fcn elt))
(setf (cdr tail) (list result-elt))
(setf tail (cdr tail))))))
(defun mapunion (fcn list &key (test #'eql) (key #'identity))
"Applies FCN to every element of LIST, unioning the results together.
Except for removal of EQL occurences, order is maintained as one might expect."
(let* ((head (list '())) (tail head))
(dolist (elt list (cdr head))
(dolist (result-elt (funcall fcn elt))
(unless (member result-elt head :test test :key key)
(setf (cdr tail) (list result-elt))
(setf tail (cdr tail)))))))
(defun union* (lists &key (test #'eql) (key #'identity))
"UNION together an arbitrary number of lists (passed in a containing list)"
(case (length lists)
(0 nil)
(1 (car lists))
(t (union* (cons (union (car lists) (cadr lists) :test test :key key)
(cddr lists))
:test test :key key))))
(defun intersection* (lists &key (test #'eql) (key #'identity))
"INTERSECTION together an arbitrary number of lists (passed in a containing list)"
(case (length lists)
(0 nil)
(1 (car lists))
(t (intersection* (cons (intersection (car lists) (cadr lists) :test test :key key)
(cddr lists))
:test test :key key))))
(defun maptree (fcn tree)
(if (listp tree)
(mapcar #'(lambda (elt) (maptree fcn elt)) tree)
(funcall fcn tree)))
(defun dotree (fcn tree)
(if (listp tree)
(mapc #'(lambda (elt) (dotree fcn elt)) tree)
(funcall fcn tree)))
;;; Apply fn to all nodes of tree, not just leaves.
(defun dotree-all (fcn tree)
(funcall fcn tree)
(if (listp tree)
(mapc #'(lambda (elt) (dotree-all fcn elt)) tree)
))
;;; works on structure with dotted lists
(defun maptree-dots (fcn tree)
(cond ((null tree) nil)
((listp tree)
(cons (maptree-dots fcn (car Tree))
(maptree-dots fcn (cdr Tree))))
(t (funcall fcn tree))))
(defun mapsum (fcn list)
(let ((result 0))
(dolist (elt list result)
(incf result (funcall fcn elt)))))
(defun mapcross (fcn list1 list2)
"Applies FCN to every combination of elements from LIST1 and LIST2,
returning the list of results. Order is maintained as one might expect."
(let* ((head (list '())) (tail head))
(dolist (e1 list1 (cdr head))
(dolist (e2 list2)
(push (funcall fcn e1 e2) (cdr tail))
(setf tail (cdr tail))))))
(defun mapsubsets (proc set)
"Map PROC over ever subset of SET"
(if (null set)
(funcall proc nil)
(mapsubsets (cdr set)
#'(lambda (ss)
(funcall proc ss)
(funcall proc (cons (car set) ss))))))
(defun split-list (predicate list)
"Returns two lists extracted from list based on PREDICATE."
(let ((wheat '()) (chaff '()))
(dolist (elt list (values (nreverse wheat) (nreverse chaff)))
(if (funcall predicate elt)
(push elt wheat) (push elt chaff)))))
; +++ key args are slow
;;; +++ rewrite to use remove-if
(defun filter (predicate list &key key &aux wheat)
"Return only the elements of list meeting PREDICATE"
(dolist (elt list (nreverse wheat))
(when (funcall predicate (if key (funcall key elt) elt))
(push elt wheat))))
(defun filter-out (predicate list &key key &aux wheat)
"Return only the elements of list not meeting PREDICATE"
(dolist (elt list (nreverse wheat))
(unless (funcall predicate (if key (funcall key elt) elt))
(push elt wheat))))
(defun find-all (item sequence &key (key #'identity) (test #'eql))
(remove-if-not #'(lambda (elt)
(funcall test item (funcall key elt)))
sequence))
;;; Not very efficient, see biolisp for better one
(defun flatten (tree)
(cond ((null tree) nil)
((listp tree)
(append (flatten (car tree))
(flatten (cdr tree))))
(t (list tree))))
(defun group (list &key (key #'identity) (test #'eql))
(let ((result nil))
(dolist (elt list)
(block elt
(dolist (cluster result)
(when (funcall test (funcall key elt) (funcall key (car cluster)))
(push-end elt cluster)
(return-from elt)))
(push (list elt) result)))
(nreverse result)))
;;; String Utilities
;;; this is the same as the CL function SUBSTITUTE, so let's flush it...
#|
(defun string-replace-char (string char0 char1 &key (start 0) (end nil))
(do ((from start)
(new-string (concatenate 'string string)))
((null from) new-string)
(setq from (position char0 string :start (1+ from) :end end))
(when from
(setf (char new-string from) char1))))
|#
(defun string+ (&rest args)
"Concatenate the elements of ARGS."
(apply #'concatenate 'string args))
;;; stolen from BioLisp
(defun string-join (string-list &optional (sep #\Space))
"Concatenates strings together and puts SEP between each joined substring"
(setq sep (string sep))
(when (null string-list) (return-from string-join ""))
(let* ((total-length 0)
(sep-length (length sep))
(no-sep (zerop sep-length)))
(dolist (s string-list) (incf total-length (+ (length s) sep-length)))
(decf total-length sep-length)
(let ((result-string (make-string total-length))
(current-pos 0))
(dolist (s string-list)
(replace result-string s :start1 current-pos)
(incf current-pos (length s))
(unless (or no-sep (>= current-pos total-length))
(replace result-string sep :start1 current-pos)
(incf current-pos sep-length)
))
result-string
)))
(defun parse-substrings (string separator)
"Return substrings separated by separator character. "
(do ((result nil (cons (subseq string finger0 finger1) result))
(finger0 0 (and finger1 (1+ finger1)))
(finger1 (position separator string) (and finger1
(position separator string :start (1+ finger1)))))
((null finger0)
(nreverse result))))
;;; This is probably not efficient
(defun big-concatenate-strings (list)
(with-output-to-string (out)
(dolist (s list)
(write-string s out))))
;;; a much-needed function. this version conses rather more than it should.
(defun string-replace (string find replace &key (start 0) (end nil) (sequence-type 'string) (test #'char-equal))
#.(doc
"Replace occurences of FIND in STRING."
"REPLACE can be a string or a function which takes the matched substring and returns a replacement (can be used to preserve case, ie).")
(do ((from start)
(substrings nil)
(subst-start t))
((null subst-start)
;; Apply is limited to some relatively small number of args
(cond ((and (eq sequence-type 'string)
(> (length substrings) 200))
(big-concatenate-strings (nreverse substrings)))
; ((null (cdr substrings))
; (car substrings))
(t (apply #'concatenate
sequence-type
(nreverse substrings)))))
(setq subst-start (search find string :start2 from :end2 end :test test))
(push (subseq string from subst-start) substrings)
(when subst-start
(setf from (+ subst-start (length find)))
(push
(if (stringp replace)
replace
(funcall replace (subseq string subst-start from)))
substrings))
))
(defun string-upper-case-p (s)
(every #'upper-case-p s))
(defun string-prefix-equals (string prefix)
"T if STRING begins with PREFIX."
(and (>= (length string) (length prefix))
(string-equal string prefix :end1 (length prefix))))
(defmacro push-string (place add)
`(setf ,place (concatenate 'string ,place ,add)))
(defun first-line (string)
(car (parse-substrings string #\Newline)))
(defun fast-string (obj)
(typecase obj
(null "")
(string obj)
(symbol (symbol-name obj)) ;what about package?
(t (fast-princ-to-string obj))))
#+CCL
(defvar *fast-princ-to-string-stream*
(ccl::%make-string-output-stream (make-array 100
:element-type 'character
:adjustable t
:fill-pointer 0)))
;;; about twice as fast
#+CCL
(defun fast-princ-to-string (obj)
(princ obj *fast-princ-to-string-stream*)
(ccl::get-output-stream-string *fast-princ-to-string-stream*))
;;; for other implementations, do the normal thing
#-CCL
(defun fast-princ-to-string (obj)
(princ-to-string obj))
(defun string-truncate (string length)
(if (or (null length)
(<= (length string) length))
string
(format nil "~A..." (subseq string 0 length))))
(defun string-truncate-to-word-boundary (string limit)
(if (or (null limit)
(<= (length string) limit))
string
(let ((boundary-pos (position #\Space string :from-end t :end limit)))
(string+ (subseq string 0 boundary-pos) "..."))))
;;; From BioBike
(defun translate-string (string from to)
#.(doc
"Changes the characters in a string from one set to another. "
"See the documentation for NTRANSLATE-STRING.")
(ntranslate-string (copy-seq string) from to))
(defun ntranslate-string (string from to)
#.(doc
"Destructively changes the characters in a string from one set to "
"another. For example: (ntranslate-string \"This\" "
"\"abcdefghijklmnopqrstuvwxyz\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\") "
"will change the string to THIS and return it. "
"NOTE THAT THIS ACTUALLY MODIFIES THE ORIGNAL STRING; "
"If you want to preserve the string, use TRANSLATE-STRING."
)
(if (and (simple-string-p string)
(simple-string-p from)
(simple-string-p to))
(ntranslate-string-fast string from to)
(loop for i below (length string)
as pos = (position (aref string i) from)
when pos
do (setf (aref string i) (aref to pos))))
string)
(defun ntranslate-string-fast (string from to)
(declare (simple-string string from to))
(let ((ls (length string)) (lf (length from)))
(declare (fixnum ls lf))
;; Completely arbitrary test for using hash algorithm.
(if (and (> lf 10) (> ls 100))
(let ((ht (make-hash-table :test 'eql)))
(loop for i fixnum below lf do
(setf (gethash (schar from i) ht) (schar to i)))
(loop for i fixnum below ls
as translation = (gethash (schar string i) ht)
when translation
do (setf (schar string i) translation)
))
(loop for i fixnum below ls
as pos = (position (schar string i) from)
when pos
do (setf (schar string i) (schar to pos)))))
string)
(defun vector->string (v &optional (len (length v)))
(let ((string (make-string len)))
(dotimes (i len)
(setf (char string i) (code-char (aref v i))))
string))
;;; inefficient, if the purpose is to make long lists manageable. Easy to fix.
(defun list-truncate (list length)
(if (> (length list) length)
(subseq list 0 length)
list))
;;; Function definition
#-ABCL ; already built in, hopefully compatible
(defmacro defsubst (name args &body body)
"Define an inline function."
`(progn
(declaim (inline ,name))
(defun ,name ,args
,@body)))
#+ABCL
(eval-when (:compile-toplevel :load-toplevel :execute)
(import 'extensions::defsubst))
#| This has vanished from Clozure
#+CCL (pushnew "subst"
(cdr (assoc 'function ccl::*define-type-alist*)))
|#
; Define a memoized function; that is, a function that caches its results in a
; hashtable and will look up prior results before computing a new one.
; See http://en.wikipedia.org/wiki/Memoization
; The function computed by BODY should be a function in the mathematical sense
; (a mapping with no state dependencies).
; Notes:
; - Comparision of new args to old is by EQUAL.
; - The hashtable is stored as the :CACHE property of the function name
; - We also define the function "reset-<name>" to clear the cache.
; +++ handle declarations in body
(defmacro def-cached-function (name arglist &body body)
`(progn
(defun ,name (&rest args)
(declare (dynamic-extent args))
(let ((ht (or (get ',name :cache)
(setf (get ',name :cache) (make-hash-table :test #'equal)))))
(multiple-value-bind (val found)
(gethash args ht)
(if found
val
(setf (gethash (copy-list args) ht)
(block ,name
(destructuring-bind ,arglist args
,@body)))))))
(defun ,(symbol-conc 'reset- name) ()
(awhen (get ',name :cache)
(clrhash it)))))
;;; alternate version
;;; - for single argument only,
;;; - uses eql as test, which ought to be more efficient
;;; - doesn't yet support the RESET- function
(defmacro def-cached-function-1 (name arglist &body body)
(assert (= 1 (length arglist)))
(let ((ht (make-hash-table :test #'eql)))
(setf (get name :cache) ht) ;allows access
`(defun ,name ,arglist
(multiple-value-bind (val found)
(gethash ,(car arglist) ,ht)
(if found
val
(setf (gethash ,(car arglist) ,ht)
(block ,name
,@body)))))))
(defmacro cached-lambda (arglist &body body)
(let ((ht (make-hash-table :test #'eql)))
`(lambda ,arglist
(multiple-value-bind (val found)
(gethash ,(car arglist) ,ht)
(if found
val
(setf (gethash ,(car arglist) ,ht)
(progn
,@body)))))))
(defun symbolize (thing)
(etypecase thing
(symbol thing)
(string (keywordize thing))))
;;; Stolen (with mods) from Alexandria
(defmacro named-lambda (name lambda-list &body body)
"Expands into a lambda-expression within whose BODY NAME denotes the
corresponding function."
(let ((fname (symbolize name)))
`(labels ((,fname ,lambda-list ,@body))
#',fname)))
;;; Randomness
(defun random-element (list)
(and list
(nth (random (length list)) list)))
(defun arand (center range)
"Return a random number from the range [center-range, center+range]"
(+ center (random (* 2.0 range)) (- range)))
;;; Numbers
(eval-when (:compile-toplevel :load-toplevel :execute)
(defconstant single-pi (coerce pi 'single-float))) ;Avoid introducing double-floats
(defconstant pi/2 (/ single-pi 2.0))
(defconstant pi/4 (/ single-pi 4.0))
(defconstant 2pi (* single-pi 2))
(defconstant degrees-to-radians (/ 2pi 360))
(defconstant radians-to-degrees (/ degrees-to-radians))
(defmacro d2r (deg)
`(* degrees-to-radians ,deg))
(defmacro d2ri (deg)
(* degrees-to-radians deg))
(defmacro r2d (rad)
`(* radians-to-degrees ,rad))
;;; Fast fixnum arithmetic
;;; Define functions such as +& that work only for fixnum arguments and results, and
;;; omit typechecking if the compiler is smart enough (in MCL, it often is -- use DISASM
;;; to check what the compiler is putting out).
(defmacro int (x) `(the fixnum ,x))
(defmacro def-fixnum-op (int-name reg-name &optional (result-type 'fixnum))
`(defmacro ,int-name (&rest args)
`(the ,',result-type (,',reg-name ,@(mapcar #'(lambda (arg) `(the fixnum ,arg)) args)))))
(def-fixnum-op +& +) ; Only addition-type ops actually get any boost in MCL2.0
(def-fixnum-op -& -)
(def-fixnum-op incf& incf)
(def-fixnum-op decf& decf)
(def-fixnum-op 1+& 1+)
(def-fixnum-op 1-& 1-)
(def-fixnum-op =& = atom)
(def-fixnum-op <& < atom)
(def-fixnum-op <=& <= atom)
(def-fixnum-op >& > atom)
(def-fixnum-op >=& >= atom)
(def-fixnum-op zerop& zerop atom)
(def-fixnum-op plusp& plusp atom)
(def-fixnum-op minusp& minusp atom)
(def-fixnum-op logand& logand)
(def-fixnum-op logior& logior)
(def-fixnum-op lognot& lognot)
(def-fixnum-op logandc1& logandc1)
(def-fixnum-op logxor& logxor)
(def-fixnum-op *& *) ; these only work in a few cases (like (* 2 <var>))
(def-fixnum-op /& /)
(def-fixnum-op mod& mod)
(defsubst max& (a b)
(if (>=& a b)
a b))
(defsubst min& (a b)
(if (<=& a b)
a b))
(defmacro ^ (x y)
`(expt ,x ,y))
(defsubst sign (num)
(cond ((plusp num) 1)
((minusp num) -1)
(t 0)))
;;; ???
(defun absmin (n min)
(if (plusp n)
(min n min)
(max n (- min))))
(defsubst abs-max (max num)
(if (<= (abs num) max)
num
(* max (sign num))))
(defun integers (from to)
(if (equal from to) (list from)
(cons from (integers (+ from (sign (- to from))) to))))
(defun log2 (x)
(/ (log x) #.(log 2)))
(defun number-of-bits (n) ;;; smallest k st 2**k>=n
(ceiling (log2 n)))
(defun bits (n &aux result)
(dotimes (bit (number-of-bits n) (nreverse result))
(unless (zerop (logand (ash 1 bit) n) )
(push bit result))))
(defun sum-list (list)
(summing (dolist (elt list) (sum elt))))
(defun average (list)
(if (null list) 0
(/ (sum-list list) (length list))))
(defun std-dev (list &aux (average (average list)))
(sqrt (/ (summing (dolist (elt list)
(sum (expt (- elt average) 2))))
(length list))))
(defun geo-mean (list)
(nth-root (apply #'* list) (length list)))
(defun nth-root (x n)
(if (> x 0) (exp (/ (log x) n))
(error "In NTH-ROOT, X=~S is not positive." x)))
(defun coerce-integer (thing &key no-error (default thing))
(typecase thing
(number thing)
(string
(multiple-value-bind (num end) (parse-integer thing :junk-allowed t)
(if (eq end (length thing))
num
(if no-error
default
(error "can't coerce ~A to a number" thing)))))
(t (if no-error default (error "can't coerce ~A to a number" thing)))))
(defun coerce-number (thing &key no-error (default thing) allow-junk?)
(typecase thing
(number thing)
(string
(handler-case
(multiple-value-bind (thing2 end) (read-from-string thing)
(if (and (numberp thing2)
(or allow-junk? (= end (length thing))))
thing2
(if no-error
default
(error "can't coerce ~A to a number" thing))))
(error (c)
(if no-error default (error "can't coerce ~A to a number: ~A" thing c)))))))
;;; Fast versions of non-arithmetic functions
(defsubst car& (cons)
(car (the cons cons)))
(defsubst cdr& (cons)
(cdr (the cons cons)))
;;; Assumes args are the right type and does no bounds checking
(defsubst svref& (vector index)
(declare (optimize (speed 3) (safety 0)))
(svref vector (the fixnum index)))
(defsetf svref& (vector index) (new-val)
`(locally (declare (optimize (speed 3) (safety 0)))
(setf (svref ,vector (the fixnum ,index)) ,new-val)))
(defsubst schar& (string index)
(declare (optimize (speed 3) (safety 0)))
(schar (the simple-string string) (the fixnum index)))
(defsetf schar& (string index) (new-val)
`(locally (declare (optimize (speed 3) (safety 0)))
(setf (schar (the simple-string ,string) (the fixnum ,index)) ,new-val)))
;;; Note: this has no speedup effect in MCL 2.0
;;; +++ not setfable
(defmacro aref& (array &rest indicies)
`(locally
(declare (optimize (speed 3) (safety 0)))
(aref ,array ,@(mapcar #'(lambda (index) `(the fixnum ,index)) indicies))))
;;; Symbols and packages
;;; package defaults to *package*, which is not always right
(defun symbol-conc (&rest parts)
(intern (apply #'concatenate 'string (mapcar 'fast-string parts))))
;;; +++ causing package problems
'(defun keyword (symbol)
(intern (string symbol) (find-package :keyword)))
(defun keywordize (symbol)
(when symbol (intern (string symbol) (find-package :keyword))))
(defun up-keywordize (symbol)
(when symbol (intern (string-upcase (string symbol)) (find-package :keyword))))
;;; CL provides no externalp function, and neither does MCL (although it keeps this info with the symbol).
(defun externalp (symbol)
(multiple-value-bind (ignore type)
(find-symbol (symbol-name symbol) (symbol-package symbol))
#-CCL (declare (ignore ignore))
(eq type :external)))
(defun add-nickname (package nickname)
(rename-package package
(package-name package)
(adjoin nickname (package-nicknames package) :test #'string-equal)))