aboutsummaryrefslogtreecommitdiff
path: root/srfi/srfi-146.scm
blob: 0aab99ca23eafb0640a7933fa12b95ea5f2a0015 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
; SPDX-FileCopyrightText: 2022 pukkamustard <pukkamustard@posteo.net>
;
; SPDX-License-Identifier: LGPL-3.0-or-later

;; This contains code taken from the SRFI sample implementation. The
;; copyright notice of the original code is as follows:

;; Copyright (C) Marc Nieper-Wißkirchen (2016, 2017).  All Rights
;; Reserved.

;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use, copy,
;; modify, merge, publish, distribute, sublicense, and/or sell copies
;; of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:

;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.

;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.

;; Changes from the sample SRFI sample implementation include:
;;
;; - Add some procedure documentation
;; - Use call/ec instead of call/cc
;;

(define-module (srfi srfi-146)

  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-2)
  #:use-module (srfi srfi-8)
  #:use-module (srfi srfi-9)
  #:use-module (srfi srfi-11)
  #:use-module (srfi srfi-128)
  #:use-module (srfi srfi-145)
  #:use-module (srfi srfi-158)

  #:use-module (ice-9 control)

  #:export (mapping mapping-unfold
	    mapping/ordered mapping-unfold/ordered
	    mapping? mapping-contains? mapping-empty? mapping-disjoint?
	    mapping-ref mapping-ref/default mapping-key-comparator
	    mapping-adjoin mapping-adjoin!
	    mapping-set mapping-set!
	    mapping-replace mapping-replace!
	    mapping-delete mapping-delete! mapping-delete-all mapping-delete-all!
	    mapping-intern mapping-intern!
	    mapping-update mapping-update! mapping-update/default mapping-update!/default
	    mapping-pop mapping-pop!
	    mapping-search mapping-search!
	    mapping-size mapping-find mapping-count mapping-any? mapping-every?
	    mapping-keys mapping-values mapping-entries
	    mapping-map mapping-map->list mapping-for-each mapping-fold
	    mapping-filter mapping-filter!
	    mapping-remove mapping-remove!
	    mapping-partition mapping-partition!
	    mapping-copy mapping->alist alist->mapping alist->mapping!
	    alist->mapping/ordered alist->mapping/ordered!
	    mapping=? mapping<? mapping>? mapping<=? mapping>=?
	    mapping-union mapping-intersection mapping-difference mapping-xor
	    mapping-union! mapping-intersection! mapping-difference! mapping-xor!
	    make-mapping-comparator
	    mapping-comparator
	    mapping-min-key mapping-max-key
	    mapping-min-value mapping-max-value
	    mapping-key-predecessor mapping-key-successor
	    mapping-range= mapping-range< mapping-range> mapping-range<= mapping-range>=
	    mapping-range=! mapping-range<! mapping-range>! mapping-range<=! mapping-range>=!
	    mapping-split
	    mapping-catenate mapping-catenate!
	    mapping-map/monotone mapping-map/monotone!
	    mapping-fold/reverse)
  #:re-export (comparator?))

(include-from-path "srfi/srfi-146/rbtree.scm")

;;; New types

(define-record-type <mapping>
  (%make-mapping comparator tree)
  mapping?
  (comparator mapping-key-comparator)
  (tree mapping-tree))

(define (make-empty-mapping comparator)
  (assume (comparator? comparator))
  (%make-mapping comparator (make-tree)))

;;; Exported procedures

;; Constructors

(define (mapping comparator . args)
  "Returns a newly allocated mapping. The comparator argument is a
SRFI 128 comparator, which is used to control and distinguish the keys
of the mapping. The args alternate between keys and values and are
used to initialize the mapping. In particular, the number of args has
to be even. Earlier associations with equal keys take precedence over
later arguments."
  (assume (comparator? comparator))
  (mapping-unfold null?
	      (lambda (args)
		(values (car args)
			(cadr args)))
	      cddr
	      args
	      comparator))

(define (mapping-unfold stop? mapper successor seed comparator)
  "Create a newly allocated mapping as if by mapping using
comparator. If the result of applying the predicate stop? to seed is
true, return the mapping. Otherwise, apply the procedure mapper to
seed. Mapper returns two values which are added to the mapping as the
key and the value, respectively. Then get a new seed by applying the
procedure successor to seed, and repeat this algorithm. Associations
earlier in the list take precedence over those that come later. "
  (assume (procedure? stop?))
  (assume (procedure? mapper))
  (assume (procedure? successor))
  (assume (comparator? comparator))
  (let loop ((mapping (make-empty-mapping comparator))
	     (seed seed))
    (if (stop? seed)
	mapping
	(receive (key value)
	    (mapper seed)
	  (loop (mapping-adjoin mapping key value)
		(successor seed))))))

(define mapping/ordered mapping)
(define mapping-unfold/ordered mapping-unfold)

;; Predicates

(define (mapping-empty? mapping)
  "Returns @code{#t} if mapping has no associations and @code{#f}
otherwise."
  (assume (mapping? mapping))
  (not (mapping-any? (lambda (key value) #t) mapping)))

(define (mapping-contains? mapping key)
  "Returns @code{#t} if @var{key} is the key of an association of
mapping and @code{#f} otherwise."
  (assume (mapping? mapping))
  (call/ec
   (lambda (return)
     (mapping-search mapping
		 key
		 (lambda (insert ignore)
		   (return #f))
		 (lambda (key value update remove)
		   (return #t))))))

(define (mapping-disjoint? mapping1 mapping2)
  "Returns @code{#t} if @var{mapping1} and @var{mapping2} have no keys
in common and @code{#f} otherwise."
  (assume (mapping? mapping1))
  (assume (mapping? mapping2))
  (call/ec
   (lambda (return)
     (mapping-for-each (lambda (key value)
		     (when (mapping-contains? mapping2 key)
		       (return #f)))
		   mapping1)
     #t)))

;; Accessors

(define mapping-ref
  (case-lambda
    ((mapping key)
     (assume (mapping? mapping))
     (mapping-ref mapping key (lambda ()
			(error "mapping-ref: key not in mapping" key))))
    ((mapping key failure)
     (assume (mapping? mapping))
     (assume (procedure? failure))
     (mapping-ref mapping key failure (lambda (value)
				value)))
    ((mapping key failure success)
     (assume (mapping? mapping))
     (assume (procedure? failure))
     (assume (procedure? success))
     ((call/ec
       (lambda (return-thunk)
	 (mapping-search mapping
			 key
			 (lambda (insert ignore)
			   (return-thunk failure))
			 (lambda (key value update remove)
			   (return-thunk (lambda () (success value)))))))))))

(define (mapping-ref/default mapping key default)
  (assume (mapping? mapping))
  (mapping-ref mapping key (lambda () default)))

;; Updaters

(define (mapping-adjoin mapping . args)
  "The mapping-adjoin procedure returns a newly allocated mapping that
uses the same comparator as the mapping mapping and contains all the
associations of mapping, and in addition new associations by
processing the arguments from left to right. The @var{args} alternate
between keys and values. Whenever there is a previous association for
a key, the previous association prevails and the new association is
skipped. It is an error to add an association to mapping whose key
that does not return @code{#t} when passed to the type test procedure
of the comparator. "
  (assume (mapping? mapping))
  (let loop ((args args)
	     (mapping mapping))
    (if (null? args)
	mapping
	(receive (mapping value)
	    (mapping-intern mapping (car args) (lambda () (cadr args)))
	  (loop (cddr args) mapping)))))

(define mapping-adjoin! mapping-adjoin)

(define (mapping-set mapping . args)
  "The mapping-set procedure returns a newly allocated mapping that
uses the same comparator as the mapping mapping and contains all the
associations of mapping, and in addition new associations by
processing the arguments from left to right. The @var{args} alternate
between keys and values. Whenever there is a previous association for
a key, it is deleted. It is an error to add an association to mapping
whose key that does not return @code{#t} when passed to the type test
procedure of the comparator. "
  (assume (mapping? mapping))
  (let loop ((args args)
	     (mapping mapping))
    (if (null? args)
	mapping
	(receive (mapping)
	    (mapping-update mapping (car args) (lambda (value) (cadr args)) (lambda () #f))
	  (loop (cddr args)
		mapping)))))

(define mapping-set! mapping-set)

(define (mapping-replace mapping key value)
  "The mapping-replace procedure returns a newly allocated mapping
that uses the same comparator as the mapping mapping and contains all
the associations of mapping except as follows: If @var{key} is equal
(in the sense of mapping's comparator) to an existing key of mapping,
then the association for that key is omitted and replaced the
association defined by the pair @var{key} and @var{value}. If there is
no such key in mapping, then mapping is returned unchanged. "
  (assume (mapping? mapping))
  (receive (mapping obj)
      (mapping-search mapping
		  key
		  (lambda (insert ignore)
		    (ignore #f))
		  (lambda (old-key old-value update remove)
		    (update key value #f)))
    mapping))

(define mapping-replace! mapping-replace)

(define (mapping-delete mapping . keys)
  "The mapping-delete procedure returns a newly allocated mapping
containing all the associations of the mapping mapping except for any
whose keys are equal (in the sense of mapping's comparator) to one or
more of the keys. Any key that is not equal to some key of the mapping
is ignored."
  (assume (mapping? mapping))
  (mapping-delete-all mapping keys))

(define mapping-delete! mapping-delete)

(define (mapping-delete-all mapping keys)
  "The mapping-delete-all and mapping-delete-all! procedures are the
same as mapping-delete and mapping-delete!, respectively, except that
they accept a single argument which is a list of keys whose
associations are to be deleted. "
  (assume (mapping? mapping))
  (assume (list? keys))
  (fold (lambda (key mapping)
	  (receive (mapping obj)
	      (mapping-search mapping
			  key
			  (lambda (insert ignore)
			    (ignore #f))
			  (lambda (old-key old-value update remove)
			    (remove #f)))
	    mapping))
	mapping keys))

(define mapping-delete-all! mapping-delete-all)

(define (mapping-intern mapping key failure)
  "Extracts the value associated to @var{key} in the mapping @var{mapping}, and
returns mapping and the value as two values. If @var{key} is not contained
in @var{mapping}, @var{failure} is invoked on no arguments. The procedure then
returns two values, a newly allocated mapping that uses the same
comparator as the mapping and contains all the associations of
mapping, and in addition a new association mapping @var{key} to the result
of invoking @var{failure}."
  (assume (mapping? mapping))
  (assume (procedure? failure))
  (call/ec
   (lambda (return)
     (mapping-search mapping
		 key
		 (lambda (insert ignore)
		   (receive (value)
		       (failure)
		     (insert value value)))
		 (lambda (old-key old-value update remove)
		   (return mapping old-value))))))

(define mapping-intern! mapping-intern)

(define mapping-update
  (case-lambda
   ((mapping key updater)
    (mapping-update mapping key updater (lambda ()
				  (error "mapping-update: key not found in mapping" key))))
   ((mapping key updater failure)
    (mapping-update mapping key updater failure (lambda (value)
					  value)))
   ((mapping key updater failure success)
    (assume (mapping? mapping))
    (assume (procedure? updater))
    (assume (procedure? failure))
    (assume (procedure? success))
    (receive (mapping obj)
	(mapping-search mapping
		    key
		    (lambda (insert ignore)
		      (insert (updater (failure)) #f))
		    (lambda (old-key old-value update remove)
		      (update key (updater (success old-value)) #f)))
      mapping))))

(define mapping-update! mapping-update)

(define (mapping-update/default mapping key updater default)
  (mapping-update mapping key updater (lambda () default)))

(define mapping-update!/default mapping-update/default)

(define mapping-pop
  (case-lambda
    "Chooses the association with the least key from @var{mapping} and
returns three values, a newly allocated mapping that uses the same
comparator as @var{mapping} and contains all associations of
@var{mapping} except the chosen one. If mapping contains no
association and @var{failure} is supplied, then @var{failure} is
invoked in tail context on no arguments and its values
returned. Otherwise, it is an error. "
    ((mapping)
     (mapping-pop mapping (lambda ()
			    (error "mapping-pop: mapping has no association"))))
    ((mapping failure)
     (assume (mapping? mapping))
     (assume (procedure? failure))
     ((call/ec
       (lambda (return-thunk)
	 (receive (key value)
	     (mapping-find (lambda (key value) #t) mapping (lambda () (return-thunk failure)))
	   (lambda ()
	     (values (mapping-delete mapping key) key value)))))))))

(define mapping-pop! mapping-pop)

(define (mapping-search mapping key failure success)
  "The mapping @var{mapping} is searched in order (that is in the
order of the stored keys) for an association with key @var{key}. If it
is not found, then the @var{failure} procedure is tail-called with two
continuation arguments, @var{insert} and @var{ignore}, and is expected
to tail-call one of them. If an association with key @var{key} is
found, then the @var{success} procedure is tail-called with the
matching key of mapping, the associated value, and two continuations,
@var{update} and @var{remove}, and is expected to tail-call one of
them.

It is an error if the continuation arguments are invoked, but not in
tail position in the @var{failure} and @var{success} procedures. It is
also an error if the @var{failure} and @var{success} procedures return
to their implicit continuation without invoking one of their
continuation arguments.

The effects of the continuations are as follows (where @var{obj} is
any Scheme object):

- Invoking @code{(insert value obj)} causes a mapping to be newly
allocated that uses the same comparator as the mapping mapping and
contains all the associations of mapping, and in addition a new
association mapping key to value.

- Invoking @code{(ignore obj)} has no effects; in particular, no new
mapping is allocated (but see below).

- Invoking @code{(update new-key new-value obj)} causes a mapping to
be newly allocated that uses the same comparator as the mapping and
contains all the associations of mapping, except for the association
with key key, which is replaced by a new association mapping new-key
to new-value.

- Invoking @code{(remove obj)} causes a mapping to be newly allocated
that uses the same comparator as the mapping and contains all the
associations of mapping, except for the association with key key.

In all cases, two values are returned: the possibly newly allocated
mapping and @var{obj}."
  (assume (mapping? mapping))
  (assume (procedure? failure))
  (assume (procedure? success))
  (call/ec
   (lambda (return)
     (let*-values
	 (((comparator)
	   (mapping-key-comparator mapping))
	  ((tree obj)
	   (tree-search comparator
			(mapping-tree mapping)
			key
			(lambda (insert ignore)
			  (failure (lambda (value obj)
				     (insert key value obj))
				   (lambda (obj)
				     (return mapping obj))))
			success)))
       (values (%make-mapping comparator tree)
	       obj)))))

(define mapping-search! mapping-search)

;; The whole mapping

(define (mapping-size mapping)
  "Returns the number of associations in @var{mapping} as an exact
integer."
  (assume (mapping? mapping))
  (mapping-count (lambda (key value)
	       #t)
	     mapping))

(define (mapping-find predicate mapping failure)
  "Returns the association with the least key of the mapping mapping
consisting of a key and value as two values such that @var{predicate}
returns a true value when invoked with @var{key} and @var{value} as
arguments, or the result of tail-calling @var{failure} with no
arguments if there is none. There are no guarantees how many times and
with which keys and values predicate is invoked. "
  (assume (procedure? predicate))
  (assume (mapping? mapping))
  (assume (procedure? failure))
  (call/ec
   (lambda (return)
     (mapping-for-each (lambda (key value)
		     (when (predicate key value)
		       (return key value)))
		   mapping)
     (failure))))

(define (mapping-count predicate mapping)
  "Returns the number of associations of the mapping @var{mapping}
that satisfy predicate (in the sense of mapping-find) as an exact
integer. There are no guarantees how many times and with which keys
and values @var{predicate} is invoked."
  (assume (procedure? predicate))
  (assume (mapping? mapping))
  (mapping-fold (lambda (key value count)
	      (if (predicate key value)
		  (+ 1 count)
		  count))
	    0 mapping))

(define (mapping-any? predicate mapping)
  "Returns @code{#t} if any association of the mapping @var{mapping}
satisfies predicate (in the sense of mapping-find), or @code{#f}
otherwise. There are no guarantees how many times and with which keys
and values predicate is invoked. "
  (assume (procedure? predicate))
  (assume (mapping? mapping))
  (call/ec
   (lambda (return)
     (mapping-for-each (lambda (key value)
		     (when (predicate key value)
		       (return #t)))
		   mapping)
     #f)))

(define (mapping-every? predicate mapping)
  "Returns @code{#t} if every association of the mapping @var{mapping}
satisfies predicate (in the sense of mapping-find), or @code{#f}
otherwise. There are no guarantees how many times and with which keys
and values predicate is invoked."
  (assume (procedure? predicate))
  (assume (mapping? mapping))
  (not (mapping-any? (lambda (key value)
		   (not (predicate key value)))
		 mapping)))

(define (mapping-keys mapping)
  "Returns a newly allocated list of all the keys in increasing order
in the mapping @var{mapping}."
  (assume (mapping? mapping))
  (mapping-fold/reverse (lambda (key value keys)
			  (cons key keys))
			'() mapping))

(define (mapping-values mapping)
  "Returns a newly allocated list of all the values in increasing
order of the keys in the mapping @var{mapping}."
  (assume (mapping? mapping))
  (mapping-fold/reverse (lambda (key value values)
			  (cons value values))
			'() mapping))

(define (mapping-entries mapping)
  "Returns two values, a newly allocated list of all the keys in the
mapping @var{mapping}, and a newly allocated list of all the values in
the mapping @var{mapping} in increasing order of the keys. "
  (assume (mapping? mapping))
  (values (mapping-keys mapping)
	  (mapping-values mapping)))

;; Mapping and folding

(define (mapping-map proc comparator mapping)
  "Applies @var{proc}, which returns two values, on two arguments, the
key and value of each association of @var{mapping} in increasing order
of the keys and returns a newly allocated mapping that uses the
comparator @var{comparator}, and which contains the results of the
applications inserted as keys and values.

Note that, when @var{proc} defines a mapping that is not 1:1 between
the keys, some of the mapped objects may be equivalent in the sense of
the comparator's equality predicate, and in this case duplicate
associations are omitted as in the mapping constructor. It is
unpredictable which one will be preserved in the result. "
  (assume (procedure? proc))
  (assume (comparator? comparator))
  (assume (mapping? mapping))
  (mapping-fold (lambda (key value mapping)
	      (receive (key value)
		  (proc key value)
		(mapping-set mapping key value)))
	    (make-empty-mapping comparator)
	    mapping))

(define (mapping-for-each proc mapping)
  "Invokes @var{proc} for every association in the mapping
@var{mapping} in increasing order of the keys, discarding the returned
values, with two arguments: the key of the association and the value
of the association. Returns an unspecified value."
  (assume (procedure? proc))
  (assume (mapping? mapping))
  (tree-for-each proc (mapping-tree mapping)))

(define (mapping-fold proc acc mapping)
  "Invokes @var{proc} for each association of the mapping
@var{mapping} in increasing order of the keys with three arguments:
the key of the association, the value of the association, and an
accumulated result of the previous invocation. For the first
invocation, @var{nil} is used as the third argument. Returns the
result of the last invocation, or @var{nil} if there was no
invocation. "
  (assume (procedure? proc))
  (assume (mapping? mapping))
  (tree-fold proc acc (mapping-tree mapping)))

(define (mapping-map->list proc mapping)
  "Calls @var{proc} for every association in increasing order of the
keys in the mapping @var{mapping} with two arguments: the key of the
association and the value of the association. The values returned by
the invocations of @var{proc} are accumulated into a list, which is
returned. "
  (assume (procedure? proc))
  (assume (mapping? mapping))
  (mapping-fold/reverse (lambda (key value lst)
			  (cons (proc key value) lst))
			'()
			mapping))

(define (mapping-filter predicate mapping)
  "Returns a newly allocated mapping with the same comparator as the
mapping @var{mapping}, containing just the associations of mapping
that satisfy @var{predicate} (in the sense of @code{mapping-find}). "
  (assume (procedure? predicate))
  (assume (mapping? mapping))
  (mapping-fold (lambda (key value mapping)
	      (if (predicate key value)
		  (mapping-set mapping key value)
		  mapping))
	    (make-empty-mapping (mapping-key-comparator mapping))
	    mapping))

(define mapping-filter! mapping-filter)

(define (mapping-remove predicate mapping)
  "Returns a newly allocated mapping with the same comparator as the
mapping @var{mapping}, containing just the associations of mapping
that do not satisfy @var{predicate} (in the sense of
@code{mapping-find})."
  (assume (procedure? predicate))
  (assume (mapping? mapping))
  (mapping-filter (lambda (key value)
		(not (predicate key value)))
	      mapping))

(define mapping-remove! mapping-remove)

(define (mapping-partition predicate mapping)
  "Returns two values: a newly allocated mapping with the same
comparator as the mapping @var{mapping} that contains just the
associations of mapping that satisfy @var{predicate}(in the sense of
@code{mapping-find}), and another newly allocated mapping, also with
the same comparator, that contains just the associations of
@var{mapping} that do not satisfy @var{predicate}."
  (assume (procedure? predicate))
  (assume (mapping? mapping))
  (values (mapping-filter predicate mapping)
	  (mapping-remove predicate mapping)))

(define mapping-partition! mapping-partition)

;; Copying and conversion

(define (mapping-copy mapping)
  "Returns a newly allocated mapping containing the associations of
the mapping @var{mapping}, and using the same comparator. "
  (assume (mapping? mapping))
  mapping)

(define (mapping->alist mapping)
  "Returns a newly allocated association list containing the
associations of the mapping in increasing order of the keys. Each
association in the list is a pair whose car is the key and whose cdr
is the associated value."
  (assume (mapping? mapping))
  (reverse
   (mapping-fold (lambda (key value alist)
		   (cons (cons key value) alist))
		 '() mapping)))

(define (alist->mapping comparator alist)
  "Returns a newly allocated mapping, created as if by mapping using
the comparator @var{comparator}, that contains the associations in the
list, which consist of a pair whose car is the key and whose cdr is
the value. Associations earlier in the list take precedence over those
that come later. "
  (assume (comparator? comparator))
  (assume (list? alist))
  (mapping-unfold null?
	      (lambda (alist)
		(let ((key (caar alist))
		      (value (cdar alist)))
		  (values key value)))
	      cdr
	      alist
	      comparator))

(define (alist->mapping! mapping alist)
  (assume (mapping? mapping))
  (assume (list? alist))
  (fold (lambda (association mapping)
	  (let ((key (car association))
		(value (cdr association)))
	    (mapping-set mapping key value)))
	mapping
	alist))

(define alist->mapping/ordered alist->mapping)
(define alist->mapping/ordered! alist->mapping!)

;; Submappings

(define mapping=?
  (case-lambda
    ((comparator mapping)
     (assume (mapping? mapping))
     #t)
    ((comparator mapping1 mapping2) (%mapping=? comparator mapping1 mapping2))
    ((comparator mapping1 mapping2 . mappings)
     (and (%mapping=? comparator mapping1 mapping2)
          (apply mapping=? comparator mapping2 mappings)))))
(define (%mapping=? comparator mapping1 mapping2)
  (and (eq? (mapping-key-comparator mapping1) (mapping-key-comparator mapping2))
       (%mapping<=? comparator mapping1 mapping2)
       (%mapping<=? comparator mapping2 mapping1)))

(define mapping<=?
  (case-lambda
    ((comparator mapping)
     (assume (mapping? mapping))
     #t)
    ((comparator mapping1 mapping2)
     (assume (comparator? comparator))
     (assume (mapping? mapping1))
     (assume (mapping? mapping2))
     (%mapping<=? comparator mapping1 mapping2))
    ((comparator mapping1 mapping2 . mappings)
     (assume (comparator? comparator))
     (assume (mapping? mapping1))
     (assume (mapping? mapping2))
     (and (%mapping<=? comparator mapping1 mapping2)
          (apply mapping<=? comparator mapping2 mappings)))))

(define (%mapping<=? comparator mapping1 mapping2)
  (assume (comparator? comparator))
  (assume (mapping? mapping1))
  (assume (mapping? mapping2))
  (let ((less? (comparator-ordering-predicate (mapping-key-comparator mapping1)))
	(equality-predicate (comparator-equality-predicate comparator))
	(gen1 (tree-generator (mapping-tree mapping1)))
	(gen2 (tree-generator (mapping-tree mapping2))))
    (let loop ((item1 (gen1))
	       (item2 (gen2)))
      (cond
       ((eof-object? item1)
	#t)
       ((eof-object? item2)
	#f)
       (else
	(let ((key1 (car item1)) (value1 (cadr item1))
	      (key2 (car item2)) (value2 (cadr item2)))
	  (cond
	   ((less? key1 key2)
	    #f)
	   ((less? key2 key1)
	    (loop item1 (gen2)))
	   ((equality-predicate value1 value2)
	    (loop (gen1) (gen2)))
	   (else
	    #f))))))))

(define mapping>?
  (case-lambda
    ((comparator mapping)
     (assume (mapping? mapping))
     #t)
    ((comparator mapping1 mapping2)
     (assume (comparator? comparator))
     (assume (mapping? mapping1))
     (assume (mapping? mapping2))
     (%mapping>? comparator mapping1 mapping2))
    ((comparator mapping1 mapping2 . mappings)
     (assume (comparator? comparator))
     (assume (mapping? mapping1))
     (assume (mapping? mapping2))
     (and (%mapping>? comparator  mapping1 mapping2)
          (apply mapping>? comparator mapping2 mappings)))))

(define (%mapping>? comparator mapping1 mapping2)
  (assume (comparator? comparator))
  (assume (mapping? mapping1))
  (assume (mapping? mapping2))
  (not (%mapping<=? comparator mapping1 mapping2)))

(define mapping<?
  (case-lambda
    ((comparator mapping)
     (assume (mapping? mapping))
     #t)
    ((comparator mapping1 mapping2)
     (assume (comparator? comparator))
     (assume (mapping? mapping1))
     (assume (mapping? mapping2))
     (%mapping<? comparator mapping1 mapping2))
    ((comparator mapping1 mapping2 . mappings)
     (assume (comparator? comparator))
     (assume (mapping? mapping1))
     (assume (mapping? mapping2))
     (and (%mapping<? comparator  mapping1 mapping2)
          (apply mapping<? comparator mapping2 mappings)))))

(define (%mapping<? comparator mapping1 mapping2)
     (assume (comparator? comparator))
     (assume (mapping? mapping1))
     (assume (mapping? mapping2))
     (%mapping>? comparator mapping2 mapping1))

(define mapping>=?
  (case-lambda
    ((comparator mapping)
     (assume (mapping? mapping))
     #t)
    ((comparator mapping1 mapping2)
     (assume (comparator? comparator))
     (assume (mapping? mapping1))
     (assume (mapping? mapping2))
     (%mapping>=? comparator mapping1 mapping2))
    ((comparator mapping1 mapping2 . mappings)
     (assume (comparator? comparator))
     (assume (mapping? mapping1))
     (assume (mapping? mapping2))
     (and (%mapping>=? comparator mapping1 mapping2)
          (apply mapping>=? comparator mapping2 mappings)))))

(define (%mapping>=? comparator mapping1 mapping2)
  (assume (comparator? comparator))
  (assume (mapping? mapping1))
  (assume (mapping? mapping2))
  (not (%mapping<? comparator mapping1 mapping2)))

;; Set theory operations

(define (%mapping-union mapping1 mapping2)
  (mapping-fold (lambda (key2 value2 mapping)
		  (receive (mapping obj)
		      (mapping-search mapping
				      key2
				      (lambda (insert ignore)
					(insert value2 #f))
				      (lambda (key1 value1 update remove)
					(update key1 value1 #f)))
		    mapping))
		mapping1 mapping2))

(define (%mapping-intersection mapping1 mapping2)
  (mapping-filter (lambda (key1 value1)
		(mapping-contains? mapping2 key1))
	      mapping1))

(define (%mapping-difference mapping1 mapping2)
  (mapping-fold (lambda (key2 value2 mapping)
	      (receive (mapping obj)
		  (mapping-search mapping
			      key2
			      (lambda (insert ignore)
				(ignore #f))
			      (lambda (key1 value1 update remove)
				(remove #f)))
		mapping))
	    mapping1 mapping2))

(define (%mapping-xor mapping1 mapping2)
  (mapping-fold (lambda (key2 value2 mapping)
	      (receive (mapping obj)
		  (mapping-search mapping
			      key2
			      (lambda (insert ignore)
				(insert value2 #f))
			      (lambda (key1 value1 update remove)
				(remove #f)))
		mapping))
	    mapping1 mapping2))

(define mapping-union
  (case-lambda
    ((mapping)
     (assume (mapping? mapping))
     mapping)
    ((mapping1 mapping2)
     (assume (mapping? mapping1))
     (assume (mapping? mapping2))
     (%mapping-union mapping1 mapping2))
    ((mapping1 mapping2 . mappings)
     (assume (mapping? mapping1))
     (assume (mapping? mapping2))
     (apply mapping-union (%mapping-union mapping1 mapping2) mappings))))
(define mapping-union! mapping-union)

(define mapping-intersection
  (case-lambda
    ((mapping)
     (assume (mapping? mapping))
     mapping)
    ((mapping1 mapping2)
     (assume (mapping? mapping1))
     (assume (mapping? mapping2))
     (%mapping-intersection mapping1 mapping2))
    ((mapping1 mapping2 . mappings)
     (assume (mapping? mapping1))
     (assume (mapping? mapping2))
     (apply mapping-intersection (%mapping-intersection mapping1 mapping2) mappings))))
(define mapping-intersection! mapping-intersection)

(define mapping-difference
  (case-lambda
    ((mapping)
     (assume (mapping? mapping))
     mapping)
    ((mapping1 mapping2)
     (assume (mapping? mapping1))
     (assume (mapping? mapping2))
     (%mapping-difference mapping1 mapping2))
    ((mapping1 mapping2 . mappings)
     (assume (mapping? mapping1))
     (assume (mapping? mapping2))
     (apply mapping-difference (%mapping-difference mapping1 mapping2) mappings))))
(define mapping-difference! mapping-difference)

(define mapping-xor
  (case-lambda
    ((mapping)
     (assume (mapping? mapping))
     mapping)
    ((mapping1 mapping2)
     (assume (mapping? mapping1))
     (assume (mapping? mapping2))
     (%mapping-xor mapping1 mapping2))
    ((mapping1 mapping2 . mappings)
     (assume (mapping? mapping1))
     (assume (mapping? mapping2))
     (apply mapping-xor (%mapping-xor mapping1 mapping2) mappings))))
(define mapping-xor! mapping-xor)

;; Additional procedures for mappings with ordererd keys

(define (mapping-min-key mapping)
  (assume (mapping? mapping))
  (call/ec
   (lambda (return)
     (mapping-fold (lambda (key value acc)
		     (return key))
		   #f mapping)
     (error "mapping-min-key: empty map"))))

(define (mapping-max-key mapping)
  (assume (mapping? mapping))
  (call/ec
   (lambda (return)
     (mapping-fold/reverse (lambda (key value acc)
			     (return key))
			   #f mapping)
     (error "mapping-max-key: empty map"))))

(define (mapping-min-value mapping)
  (assume (mapping? mapping))
  (call/ec
   (lambda (return)
     (mapping-fold (lambda (key value acc)
		     (return value))
		   #f mapping)
     (error "mapping-min-value: empty map"))))

(define (mapping-max-value mapping)
  (assume (mapping? mapping))
  (call/ec
   (lambda (return)
     (mapping-fold/reverse (lambda (key value acc)
			     (return value))
			   #f mapping)
     (error "mapping-max-value: empty map"))))

(define (mapping-min-entry mapping)
  (assume (mapping? mapping))
  (call/ec
   (lambda (return)
     (mapping-fold (lambda (key value acc)
		     (return key value))
		   #f mapping)
     (error "mapping-min-key: empty map"))))

(define (mapping-max-entry mapping)
  (assume (mapping? mapping))
  (call/ec
   (lambda (return)
     (mapping-fold/reverse (lambda (key value acc)
			     (return key value))
			   #f mapping)
     (error "mapping-max-key: empty map"))))

(define (mapping-key-predecessor mapping obj failure)
  (assume (mapping? mapping))
  (assume (procedure? failure))
  (tree-key-predecessor (mapping-key-comparator mapping) (mapping-tree mapping) obj failure))

(define (mapping-key-successor mapping obj failure)
  (assume (mapping? mapping))
  (assume (procedure? failure))
  (tree-key-successor (mapping-key-comparator mapping) (mapping-tree mapping) obj failure))

(define (mapping-range= mapping obj)
  (assume (mapping? mapping))
  (let ((comparator (mapping-key-comparator mapping)))
    (receive (tree< tree<= tree= tree>= tree>)
	(tree-split comparator (mapping-tree mapping) obj)
      (%make-mapping comparator tree=))))

(define (mapping-range< mapping obj)
  (assume (mapping? mapping))
  (let ((comparator (mapping-key-comparator mapping)))
    (receive (tree< tree<= tree= tree>= tree>)
	(tree-split comparator (mapping-tree mapping) obj)
      (%make-mapping comparator tree<))))

(define (mapping-range<= mapping obj)
  (assume (mapping? mapping))
  (let ((comparator (mapping-key-comparator mapping)))
    (receive (tree< tree<= tree= tree>= tree>)
	(tree-split comparator (mapping-tree mapping) obj)
      (%make-mapping comparator tree<=))))

(define (mapping-range> mapping obj)
  (assume (mapping? mapping))
  (let ((comparator (mapping-key-comparator mapping)))
    (receive (tree< tree<= tree= tree>= tree>)
	(tree-split comparator (mapping-tree mapping) obj)
      (%make-mapping comparator tree>))))

(define (mapping-range>= mapping obj)
  (assume (mapping? mapping))
  (assume (mapping? mapping))
  (let ((comparator (mapping-key-comparator mapping)))
    (receive (tree< tree<= tree= tree>= tree>)
	(tree-split comparator (mapping-tree mapping) obj)
      (%make-mapping comparator tree>=))))

(define mapping-range=! mapping-range=)
(define mapping-range<! mapping-range<)
(define mapping-range>! mapping-range>)
(define mapping-range<=! mapping-range<=)
(define mapping-range>=! mapping-range>=)

(define (mapping-split mapping obj)
  (assume (mapping? mapping))
  (let ((comparator (mapping-key-comparator mapping)))
    (receive (tree< tree<= tree= tree>= tree>)
	(tree-split comparator (mapping-tree mapping) obj)
      (values (%make-mapping comparator tree<)
	      (%make-mapping comparator tree<=)
	      (%make-mapping comparator tree=)
	      (%make-mapping comparator tree>=)
	      (%make-mapping comparator tree>)))))

(define mapping-split! mapping-split)

(define (mapping-catenate comparator mapping1 pivot-key pivot-value mapping2)
  (assume (comparator? comparator))
  (assume (mapping? mapping1))
  (assume (mapping? mapping2))
  (%make-mapping comparator (tree-catenate (mapping-tree mapping1)
					   pivot-key
					   pivot-value
					   (mapping-tree mapping2))))

(define mapping-catenate! mapping-catenate)

(define (mapping-map/monotone proc comparator mapping)
  (assume (procedure? proc))
  (assume (comparator? comparator))
  (assume (mapping? mapping))
  (%make-mapping comparator (tree-map proc (mapping-tree mapping))))

(define mapping-map/monotone! mapping-map/monotone)

(define (mapping-fold/reverse proc acc mapping)
  (assume (procedure? proc))
  (assume (mapping? mapping))
  (tree-fold/reverse proc acc (mapping-tree mapping)))

;; Comparators

(define (mapping-equality comparator)
  (assume (comparator? comparator))
  (lambda (mapping1 mapping2)
    (mapping=? comparator mapping1 mapping2)))

(define (mapping-ordering comparator)
  (assume (comparator? comparator))
  (let ((value-equality (comparator-equality-predicate comparator))
	(value-ordering (comparator-ordering-predicate comparator)))
    (lambda (mapping1 mapping2)
      (let* ((key-comparator (mapping-key-comparator mapping1))
	     (equality (comparator-equality-predicate key-comparator))
	     (ordering (comparator-ordering-predicate key-comparator))
	     (gen1 (tree-generator (mapping-tree mapping1)))
	     (gen2 (tree-generator (mapping-tree mapping2))))
	(let loop ()
	  (let ((item1 (gen1)) (item2 (gen2)))
	    (cond
	     ((eof-object? item1)
	      (not (eof-object? item2)))
	     ((eof-object? item2)
	      #f)
	     (else
	      (let ((key1 (car item1)) (value1 (cadr item1))
		    (key2 (car item2)) (value2 (cadr item2)))
		(cond
		 ((equality key1 key2)
		  (if (value-equality value1 value2)
		      (loop)
		      (value-ordering value1 value2)))
		 (else
		  (ordering key1 key2))))))))))))

(define (make-mapping-comparator comparator)
  (make-comparator mapping? (mapping-equality comparator) (mapping-ordering comparator) #f))

(define mapping-comparator (make-mapping-comparator (make-default-comparator)))

(comparator-register-default! mapping-comparator)