-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtensor.sml
4388 lines (3901 loc) · 152 KB
/
tensor.sml
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
(*
Copyright (c) Juan Jose Garcia Ripoll and Ivan Raikov.
All rights reserved.
Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following
conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
3. All advertising materials mentioning features or use of this
software must display the following acknowledgement:
This product includes software developed by Juan Jose
Garcia Ripoll.
4. The name of Juan Jose Garcia Ripoll may not be used to endorse
or promote products derived from this software without
specific prior written permission.
*)
(*
structure IntArray =
struct
open Array
type array = int array
type vector = int vector
type elem = int
structure Vector =
struct
open Vector
type vector = int Vector.vector
type elem = int
end
fun map f a = tabulate(length a, fn x => (f (sub(a,x))))
fun mapi f a = tabulate(length a, fn x => (f (x,sub(a,x))))
fun map2 f a b = tabulate(length a, fn x => (f(sub(a,x),sub(b,x))))
end
*)
signature MONO_VECTOR =
sig
type vector
type elem
val maxLen : int
val fromList : elem list -> vector
val tabulate : (int * (int -> elem)) -> vector
val length : vector -> int
val sub : (vector * int) -> elem
val extract : (vector * int * int option) -> vector
val concat : vector list -> vector
val mapi : ((int * elem) -> elem) -> (vector * int * int option) -> vector
val map : (elem -> elem) -> vector -> vector
val appi : ((int * elem) -> unit) -> (vector * int * int option) -> unit
val app : (elem -> unit) -> vector -> unit
val foldli : ((int * elem * 'a) -> 'a) -> 'a -> (vector * int * int option) -> 'a
val foldri : ((int * elem * 'a) -> 'a) -> 'a -> (vector * int * int option) -> 'a
val foldl : ((elem * 'a) -> 'a) -> 'a -> vector -> 'a
val foldr : ((elem * 'a) -> 'a) -> 'a -> vector -> 'a
end
structure Loop =
struct
fun all (a, b, f) =
if a > b then
true
else if f a then
all (a+1, b, f)
else
false
fun any (a, b, f) =
if a > b then
false
else if f a then
true
else
any (a+1, b, f)
fun find (a, b, f) =
if a > b
then NONE
else (let
val v1 = f a
in
case v1 of
SOME _ => v1
| NONE => (let val v2 = f b
in case v2 of SOME _ => v2 | NONE => find (a+1, b-1, f)
end)
end)
fun app (a, b, f) =
if a < b then
(f a; app (a+1, b, f))
else
()
fun app2 (a1, b1, a2, b2, f) =
if ((a1 < b1) andalso (a2 < b2)) then
(f (a1, a2); app2 (a1+1, b1, a2+1, b2, f))
else ()
fun app3 (a1, b1, a2, b2, a3, b3, f) =
if ((a1 < b1) andalso (a2 < b2) andalso (a3 < b3)) then
(f (a1, a2, a3); app3 (a1+1, b1, a2+1, b2, a3+1, b3, f))
else ()
fun app' (a, b, d, f) =
if a < b then
(f a; app' (a+d, b, d, f))
else
()
fun appi' (a, b, d, f) =
if a < b then
(f a; appi' (a+d, b, d, f))
else
()
fun foldi (a, b, f, init) =
if a < b then
foldi (a+1, b, f, f (a, init))
else
init
end
(*
INDEX -Signature-
Indices are a enumerable finite set of data with an order and a map
to a continous nonnegative interval of integers. In the sample
implementation, Index, each index is a list of integers,
[i1,...,in]
and each set of indices is defined by a shape, which has the same
shape of an index but with each integer incremented by one
shape = [k1,...,kn]
0 <= i1 < k1
type storage = RowMajor | ColumnMajor
order : storage
Identifies:
1) the underlying algorithms for this structure
2) the most significant index
3) the index that varies more slowly
4) the total order
RowMajor means that first index is most significant and varies
more slowly, while ColumnMajor means that last index is the most
significant and varies more slowly. For instance
RowMajor => [0,0]<[0,1]<[1,0]<[1,1] (C, C++, Pascal)
ColumnMajor => [0,0]>[1,0]>[0,1]>[1,1] (Fortran, Matlab)
last shape
first shape
Returns the last/first index that belongs to the set defined by
'shape'.
inBounds shape index
Checkes whether 'index' belongs to the set defined by 'shape'.
toInt shape index
As we said, indices can be sorted and mapped to a finite set of
integers. 'toInt' obtains the integer number that corresponds to
a certain index.
indexer shape
It is equivalent to the partial evaluation 'toInt shape' but
optimized for 'shape'.
next shape index
prev shape index
next' shape index
prev' shape index
Obtain the following or previous index to the one we supply.
next and prev return an object of type 'index option' so that
if there is no such following/previous, the output is NONE.
On the other hand, next'/prev' raise an exception when the
output is not well defined and their output is always of type
index. next/prev/next'/prev' raise an exception if 'index'
does not belong to the set of 'shape'.
all shape f
any shape f
app shape f
Iterates 'f' over every index of the set defined by 'shape'.
'all' stops when 'f' first returns false, 'any' stops when
'f' first returns true and 'app' does not stop and discards the
output of 'f'.
compare(a,b)
Returns LESS/GREATER/EQUAL according to the total order which
is defined in the set of all indices.
<,>,eq,<=,>=,<>
Reduced comparisons which are defined in terms of 'compare'.
+,-
Index addition and subtraction
incr,decr
Index increment and decrement by a constant
scale
Index multiplication by a constant
validShape t
validIndex t
Checks whether 't' conforms a valid shape or index.
*)
signature INDEX =
sig
type t
type indexer = t -> int
datatype storage = RowMajor | ColumnMajor
exception Index
exception Shape
val order : storage
val toInt : t -> t -> int
val length : t -> int
val first : t -> t
val last : t -> t
val next : t -> t -> t option
val prev : t -> t -> t option
val next' : t -> t -> t
val prev' : t -> t -> t
val indexer : t -> (t -> int)
val inBounds : t -> t -> bool
val compare : t * t -> order
val < : t * t -> bool
val > : t * t -> bool
val eq : t * t -> bool
val <= : t * t -> bool
val >= : t * t -> bool
val <> : t * t -> bool
val - : t * t -> t
val + : t * t -> t
val decr : int -> t -> t
val incr : int -> t -> t
val scale : int -> t -> t
val validShape : t -> bool
val validIndex : t -> bool
val all : t -> (t -> bool) -> bool
val any : t -> (t -> bool) -> bool
val app : t -> (t -> unit) -> unit
end
structure Index : INDEX =
struct
type t = int list
type indexer = t -> int
datatype storage = RowMajor | ColumnMajor
exception Index
exception Shape
val order = ColumnMajor
fun validShape shape = List.all (fn x => x > 0) shape
fun validIndex index = List.all (fn x => x >= 0) index
fun toInt shape index =
let fun loop ([], [], accum, p) = accum
| loop ([], _, _, _) = raise Index
| loop (_, [], _, _) = raise Index
| loop (i::ri, l::rl, accum, p) =
if (i >= 0) andalso (i < l) then
loop (ri, rl, i * p + accum, p * l)
else
raise Index
in loop (index, shape, 0, 1)
end
(* ----- CACHED LINEAR INDEXER -----
An indexer is a function that takes a list of
indices, validates it and produces a nonnegative
integer number. In short, the indexer is the
mapper from indices to element positions in
arrays.
'indexer' builds such a mapper by optimizing
the most common cases, which are 1d and 2d
tensors.
*)
local
fun doindexer [] _ = raise Shape
| doindexer [a] [dx] =
let fun f [x] = if (x > 0) andalso (x < a)
then x
else raise Index
| f _ = raise Index
in f end
| doindexer [a,b] [dx, dy] =
let fun f [x,y] = if ((x >= 0) andalso (x < a) andalso
(y >= 0) andalso (y < b))
then x + dy * y
else raise Index
| f _ = raise Index
in f end
| doindexer [a,b,c] [dx,dy,dz] =
let fun f [x,y,z] = if ((x >= 0) andalso (x < a) andalso
(y >= 0) andalso (y < b) andalso
(z >= 0) andalso (z < c))
then x + dy * y + dz * z
else raise Index
| f _ = raise Index
in f end
| doindexer shape memo =
let fun f [] [] accum [] = accum
| f (fact::rf) (ndx::ri) accum (dim::rd) =
(if (ndx >= 0) andalso (ndx < dim) then
f rf ri (accum + ndx * fact) rd
else
raise Index)
| f _ [] _ _ = raise Index
| f [] _ _ _ = raise Index
| f _ _ _ [] = raise Index
in f shape memo 0
end
in
fun indexer shape =
let fun memoize accum [] = []
| memoize accum (dim::rd) =
accum :: (memoize (dim * accum) rd)
in if validShape shape then
doindexer shape (memoize 1 shape)
else
raise Shape
end
end
fun length shape =
let fun prod (a,b) =
if a > 0 then a*b else raise Shape
in foldl prod 1 shape
end
fun first shape = map (fn x => 0) shape
fun last [] = []
| last (size :: rest) = size - 1 :: last rest
fun next' [] [] = raise Subscript
| next' _ [] = raise Index
| next' [] _ = raise Index
| next' (dimension::restd) (index::resti) =
if (index + 1) < dimension then
(index + 1) :: resti
else
0 :: (next' restd resti)
fun prev' [] [] = raise Subscript
| prev' _ [] = raise Index
| prev' [] _ = raise Index
| prev' (dimension::restd) (index::resti) =
if (index > 0) then
(index - 1) :: resti
else
(dimension - 1) :: (prev' restd resti)
fun next shape index = (SOME (next' shape index)) handle
Subscript => NONE
fun prev shape index = (SOME (prev' shape index)) handle
Subscript => NONE
fun inBounds shape index =
ListPair.all (fn (x,y) => (x >= 0) andalso (x < y))
(index, shape)
fun compare ([],[]) = EQUAL
| compare (_, []) = raise Index
| compare ([],_) = raise Index
| compare (a::ra, b::rb) =
case Int.compare (a,b) of
EQUAL => compare (ra,rb)
| LESS => LESS
| GREATER => GREATER
local
fun iterator a inner =
let fun loop accum f =
let fun innerloop i =
if i < a then
if inner (i::accum) f then
innerloop (i+1)
else
false
else
true
in innerloop 0
end
in loop
end
fun build_iterator [a] =
let fun loop accum f =
let fun innerloop i =
if i < a then
if f (i::accum) then
innerloop (i+1)
else
false
else
true
in innerloop 0
end
in loop
end
| build_iterator (a::rest) = iterator a (build_iterator rest)
| build_iterator [] = raise Shape
in
fun all shape = build_iterator shape []
end
local
fun iterator a inner =
let fun loop accum f =
let fun innerloop i =
if i < a then
if inner (i::accum) f then
true
else
innerloop (i+1)
else
false
in innerloop 0
end
in loop
end
fun build_iterator [a] =
let fun loop accum f =
let fun innerloop i =
if i < a then
if f (i::accum) then
true
else
innerloop (i+1)
else
false
in innerloop 0
end
in loop
end
| build_iterator (a::rest) = iterator a (build_iterator rest)
| build_iterator [] = raise Shape
in
fun any shape = build_iterator shape []
end
local
fun iterator a inner =
let fun loop accum f =
let fun innerloop i =
case i < a of
true => (inner (i::accum) f; innerloop (i+1))
| false => ()
in innerloop 0
end
in loop
end
fun build_iterator [a] =
let fun loop accum f =
let fun innerloop i =
case i < a of
true => (f (i::accum); innerloop (i+1))
| false => ()
in innerloop 0
end
in loop
end
| build_iterator (a::rest) = iterator a (build_iterator rest)
| build_iterator [] = raise Shape
in
fun app shape = build_iterator shape []
end
fun a < b = compare(a,b) = LESS
fun a > b = compare(a,b) = GREATER
fun eq (a, b) = compare(a,b) = EQUAL
fun a <> b = not (a = b)
fun a <= b = not (a > b)
fun a >= b = not (a < b)
fun a - b = ListPair.map Int.- (a,b)
fun a + b = ListPair.map Int.+ (a,b)
fun decr n a = List.map (fn (x) => Int.-(x,n)) a
fun incr n a = List.map (fn (x) => Int.+(x,n)) a
fun scale n a = List.map (fn (x) => Int.*(x,n)) a
end
signature RANGE =
sig
structure Index : INDEX
type index = Index.t
type t
exception Range
val fromto : index -> index * index -> t
val fromto' : index -> index * index -> t
val upto : index -> index -> t
val below : index -> index -> t
val first : t -> index
val last : t -> index
val length : t -> int
val shape : t -> index
val shapes : t -> index list
val inRange : t -> index -> bool
val next : t -> index -> index option
val prev : t -> index -> index option
val ranges : index -> ((index * index) list) -> t
val iteri : (index -> bool) -> t -> bool
val iteri2 : (index * index -> bool) -> (t * t) -> bool
val iteri_range : (index * index -> bool) -> t -> bool
val iteri2_range : (((index * index) * (index * index)) -> bool) -> (t * t) -> bool
val foldi_range : (((index * index) * 'a) -> 'a) -> 'a -> t -> 'a
end
structure Range : RANGE =
struct
structure Index = Index
type index = Index.t
datatype t = RangeEmpty | RangeIn of index * index * index | RangeSet of index * ((index * index) list)
exception Range
local
fun next'' [] [] [] = raise Range
| next'' [] _ _ = raise Index.Index
| next'' _ [] _ = raise Index.Index
| next'' _ _ [] = raise Index.Index
| next'' (low::rl) (up::ru) (index::ri) =
if index < up then
index + 1 :: ri
else
low :: (next'' rl ru ri)
fun prev'' [] [] [] = raise Range
| prev'' [] _ _ = raise Index.Index
| prev'' _ [] _ = raise Index.Index
| prev'' _ _ [] = raise Index.Index
| prev'' (low::rl) (up::ru) (index::ri) =
if index > low then
index - 1 :: ri
else
up :: (prev'' rl ru ri)
(* Builds the simple loop
for i := first to last
if not (g (i::ndx)) then
break
endfor;
*)
fun simple_loop (first : int) (last : int) =
let fun loop (ndx : index) (g: index -> bool) =
let fun innerloop i =
if i > last then
true
else if g (i::ndx) then
innerloop (i+1)
else
false
in innerloop first end
in loop end
(* Builds the nested loop
for i := first to last
if not (f (i:ndx) g) then
break
endfor
*)
fun nested_loop f (first : int) (last : int) =
let fun loop (ndx: index) (g: index -> bool) =
let fun innerloop i =
(if i > last then
true
else if (f (i::ndx) g) then
innerloop (i+1)
else
false)
in
innerloop first
end
in loop end
fun build_iterator ([a] : index) ([b] : index) =
simple_loop a b
| build_iterator (a::ra) (b::rb) =
nested_loop (build_iterator ra rb) a b
| build_iterator [] _ = raise Range
| build_iterator _ [] = raise Range
fun simple_loop2 (first : int) (last : int) (first' : int) (last' : int) =
let fun loop (ndx : index) (ndx' : index) (g: index * index -> bool) =
let fun innerloop (i,j) =
if i > last andalso j > last' then
true
else if g (i::ndx,j::ndx') then
innerloop (i+1,j+1)
else
false
in innerloop (first,first') end
in loop end
fun nested_loop2 f (first : int) (last : int) (first' : int) (last' : int) =
let fun loop (ndx: index) (ndx': index) (g: index * index -> bool) =
let fun innerloop (i,j) =
(if i > last andalso j > last' then
true
else if (f (i::ndx) (j::ndx') g) then
innerloop (i+1,j+1)
else
false)
in
innerloop (first,first')
end
in loop end
fun build_iterator2 ([a] : index) ([b] : index) ([a'] : index) ([b'] : index) =
simple_loop2 a b a' b'
| build_iterator2 (a::ra) (b::rb) (a'::ra') (b'::rb') =
nested_loop2 (build_iterator2 ra rb ra' rb') a b a' b'
| build_iterator2 _ _ _ [] = raise Range
| build_iterator2 _ _ [] _ = raise Range
| build_iterator2 _ [] _ _ = raise Range
| build_iterator2 [] _ _ _ = raise Range
fun simple_range_loop (first : int) (last : int) (ndx: index)
(f: (index * index) -> bool) =
f ((first::ndx,last::ndx))
fun nested_range_loop (g: index -> ((index * index) -> bool) -> bool)
(first : int) (last : int) =
let
fun loop (ndx: index) (f: (index * index) -> bool) =
let
fun innerloop i =
(if i > last then
true
else
if (g (i::ndx) f)
then innerloop (i+1)
else false)
in
innerloop first
end
in loop end
fun build_range_iterator ([a] : index) ([b] : index) =
simple_range_loop a b
| build_range_iterator (a::ra) (b::rb) =
nested_range_loop (build_range_iterator ra rb) a b
| build_range_iterator [] _ = raise Range
| build_range_iterator _ [] = raise Range
fun simple_range_loop2 (first : int) (last : int) (first' : int) (last' : int)
(ndx: index) (ndx': index)
(f: ((index * index) * (index * index)) -> bool) =
f ((first::ndx,last::ndx),(first'::ndx',last'::ndx'))
fun nested_range_loop2 f (first : int) (last : int) (first' : int) (last' : int) =
let fun loop (ndx: index) (ndx': index) (g: ((index * index) * (index * index)) -> bool) =
let fun innerloop (i,j) =
(if i > last andalso j > last' then
true
else if (f (i::ndx) (j::ndx') g) then
innerloop (i+1,j+1)
else
false)
in
innerloop (first,first')
end
in loop end
fun build_range_iterator2 ([a] : index) ([b] : index) ([a'] : index) ([b'] : index) =
simple_range_loop2 a b a' b'
| build_range_iterator2 (a::ra) (b::rb) (a'::ra') (b'::rb') =
nested_range_loop2 (build_range_iterator2 ra rb ra' rb') a b a' b'
| build_range_iterator2 _ _ _ [] = raise Range
| build_range_iterator2 _ _ [] _ = raise Range
| build_range_iterator2 _ [] _ _ = raise Range
| build_range_iterator2 [] _ _ _ = raise Range
fun simple_range_fold (first : int) (last : int) (ndx: index)
(f: ((index * index) * 'a) -> 'a) (init: 'a) =
f ((first::ndx,last::ndx),init)
fun nested_range_fold (g: index -> (((index * index) * 'a) -> 'a) -> 'a -> 'a)
(first : int) (last : int) =
let
fun loop (ndx: index) (f: ((index * index) * 'a) -> 'a) (init: 'a) =
let
fun innerloop i init =
(if i > last then
init
else
innerloop (i+1) (g (i::ndx) f init))
in
innerloop first init
end
in loop end
fun build_range_fold ([a] : index) ([b] : index) =
simple_range_fold a b
| build_range_fold (a::ra) (b::rb) =
nested_range_fold (build_range_fold ra rb) a b
| build_range_fold [] _ = raise Range
| build_range_fold _ [] = raise Range
in
(* ----- CONSTRUCTORS ----- *)
fun fromto shape (lo, up) =
if (Index.validShape shape) andalso (Index.validIndex lo) andalso (Index.validIndex up) andalso
(Index.inBounds shape lo) andalso (Index.inBounds shape up) andalso Index.<= (lo,up)
then RangeIn(shape,lo,up)
else RangeEmpty
fun fromto' shape (lo, up) = fromto shape (lo, (Index.prev' shape up))
fun upto shape index = fromto shape (Index.first index, index)
fun below shape index = fromto' shape (Index.first index, index)
fun range_append ((lo,up),((lo',up')::ranges)) =
if Index.< (up,lo') then ((lo,up)::(lo',up')::ranges) else
(if Index.> (up,up') then (lo',up')::(range_append ((lo,up),ranges)) else
(if Index.> (lo,lo') then ((lo',up')::ranges) else ((lo,up')::ranges) ))
| range_append ((lo,up),[]) = [(lo,up)]
fun ranges' shape ((lo, up) :: rest) =
(if (Index.validShape shape) andalso (Index.validIndex lo) andalso (Index.validIndex up) andalso
(Index.inBounds shape lo) andalso (Index.inBounds shape up) andalso Index.< (lo,up)
then range_append ((lo,up), (ranges' shape rest)) else (ranges' shape rest))
| ranges' shape ([]) = []
fun ranges shape xs =
let val set = ranges' shape xs
in
case set of
[] => RangeEmpty
| [(lo,up)] => RangeIn (shape,lo,up)
| _ =>
let
val shapes = List.map (fn (lo,up) => (ListPair.map (fn (x,y) => y-x+1) (lo,up))) set
val shape' = List.foldl (fn(s,ax) => (ListPair.map (fn (x,y) => x+y) (s, ax)))
(hd shapes)
(tl shapes)
in
RangeSet (shape,set)
end
end
fun length RangeEmpty = 0
| length (RangeIn(shape,lo,up)) =
let fun diff (x,y) = (y-x+1) in
Index.length (ListPair.map diff (lo,up))
end
| length (RangeSet(shape,set)) =
let fun diff (x,y) = (y-x+1) in
foldl (fn ((lo,up),ax) => (Index.length (ListPair.map diff (lo,up))) + ax)
0 set
end
fun shapes RangeEmpty = []
| shapes (RangeIn(shape,lo,up)) =
let fun diff (x,y) = (y-x+1)
in
[ListPair.map diff (lo,up)]
end
| shapes (RangeSet(shape,set)) =
let fun diff (x,y) = (y-x+1) in
List.map (fn (lo,up) => ListPair.map diff (lo,up)) set
end
fun shape RangeEmpty = raise Empty
| shape r =
let val shs = shapes r
in
case shs of
[sh] => sh
| _ => foldl Index.+ (hd shs) (tl shs)
end
fun first RangeEmpty = raise Range
| first (RangeIn(shape,lo,up)) = lo
| first (RangeSet(shape,(lo,up)::_)) = lo
| first (RangeSet(shape,[])) = raise Range
fun last RangeEmpty = raise Range
| last (RangeIn(shape,lo,up)) = up
| last (RangeSet(shape,set)) = let val (lo,up) = List.last set in up end
(* ----- PREDICATES & OPERATIONS ----- *)
fun inRange RangeEmpty _ = false
| inRange (RangeIn(shape,lo,up)) ndx =
(ListPair.all (op <=) (lo,ndx)) andalso (ListPair.all (op <=) (ndx,up))
| inRange (RangeSet(shape,set)) ndx =
List.exists (fn ((lo,up)) => (ListPair.all (op <=) (lo,ndx)) andalso (ListPair.all (op <=) (ndx,up))) set
fun next''' lo up index =
(case Index.order of
Index.RowMajor => (next'' lo up index)
| Index.ColumnMajor => (List.rev (next'' (List.rev lo) (List.rev up) (List.rev index))))
fun prev''' lo up index =
(case Index.order of
Index.RowMajor => (prev'' lo up index)
| Index.ColumnMajor => (List.rev (prev'' (List.rev lo) (List.rev up) (List.rev index))))
fun next RangeEmpty _ = NONE
| next (RangeIn(shape,lo,up)) index =
(SOME (next''' lo up index) handle Range => NONE)
| next (RangeSet(shape,set)) index =
let val m = List.find (fn ((lo,up)) => (Index.<=(lo,index)) andalso (Index.<=(index,up))) set
in
case m of NONE => NONE
| SOME (lo,up) => (SOME (next''' lo up index) handle Range => NONE)
end
fun prev RangeEmpty _ = NONE
| prev (RangeIn(shape,lo,up)) index =
(SOME (prev''' lo up index) handle Range => NONE)
| prev (RangeSet(shape,set)) index =
let val m = List.find (fn ((lo,up)) => (Index.<=(lo,index)) andalso (Index.<=(index,up))) set
in
case m of NONE => NONE
| SOME (lo,up) => (SOME (prev''' lo up index) handle Range => NONE)
end
fun next' RangeEmpty _ = raise Range
| next' (RangeIn(shape,lo,up)) index =
(next''' lo up index)
| next' (RangeSet(shape,set)) index =
let val m = List.find (fn ((lo,up)) => (Index.<=(lo,index)) andalso (Index.<=(index,up))) set
val (lo,up) = valOf m
in
(next''' lo up index)
end
fun prev' RangeEmpty _ = raise Range
| prev' (RangeIn(shape,lo,up)) index =
prev''' lo up index
| prev' (RangeSet(shape,set)) index =
let val m = List.find (fn ((lo,up)) => (Index.<=(lo,index)) andalso (Index.<=(index,up))) set
val (lo,up) = valOf m
in
prev''' lo up index
end
(* ----- ITERATION ----- *)
(* Builds an iterator that applies 'f' sequentially to
all the indices in the range, *)
fun iteri f RangeEmpty = f []
| iteri (f: index -> bool) (RangeIn(shape,lo: index,up: index)) =
(case Index.order of
Index.RowMajor => ((build_iterator lo up) [] f)
| Index.ColumnMajor => ((build_iterator (List.rev lo) (List.rev up)) [] f))
| iteri (f: index -> bool) (RangeSet(shape,set)) =
(case Index.order of
Index.RowMajor => (List.all (fn (lo,up) => ((build_iterator lo up) [] f)) set)
| Index.ColumnMajor => (List.all (fn (lo,up) => ((build_iterator (List.rev lo) (List.rev up)) [] f)) set))
(* Builds an interator that applies 'f' sequentially to
all the indices of the two ranges, *)
fun iteri2 f (RangeEmpty,RangeEmpty) = f ([],[])
| iteri2 (f: index * index -> bool) (RangeIn(shape,lo: index,up: index),RangeIn(shape',lo': index,up': index)) =
(case Index.order of
Index.RowMajor => ((build_iterator2 lo up lo' up') [] [] f )
| Index.ColumnMajor => ((build_iterator2 (List.rev lo) (List.rev up) (List.rev lo') (List.rev up')) [] [] f ))
| iteri2 (f: index * index -> bool) (RangeSet(shape,set),RangeSet(shape',set')) =
(case Index.order of
Index.RowMajor => (ListPair.all (fn ((lo,up),(lo',up')) =>
(build_iterator2 lo up lo' up') [] [] f)
(set,set') )
| Index.ColumnMajor => (ListPair.all (fn ((lo,up),(lo',up')) =>
(build_iterator2 (List.rev lo) (List.rev up) (List.rev lo') (List.rev up')) [] [] f)
(set,set') ))
| iteri2 f (_,_) = raise Range
(* Builds an iterator that applies 'f' sequentially to
all the ranges of contiguous indices (i,j) *)
fun iteri_range f RangeEmpty = f ([],[])
| iteri_range (f: index * index -> bool) (RangeIn(shape,lo: index,up: index)) =
(case Index.order of
Index.RowMajor => ((build_range_iterator lo up) [] f)
| Index.ColumnMajor => ((build_range_iterator (List.rev lo) (List.rev up)) [] f))
| iteri_range (f: index * index -> bool) (RangeSet(shape,set)) =
(case Index.order of
Index.RowMajor => (List.all (fn (lo,up) => ((build_range_iterator lo up) [] f)) set)
| Index.ColumnMajor => (List.all (fn (lo,up) => ((build_range_iterator (List.rev lo) (List.rev up)) [] f)) set))
(* Builds an interator that applies 'f' sequentially to
all the contiguous indices of the two ranges, *)
fun iteri2_range f (RangeEmpty,RangeEmpty) = f (([],[]),([],[]))
| iteri2_range (f: ((index * index) * (index * index)) -> bool)
(RangeIn(shape,lo: index,up: index),RangeIn(shape',lo': index,up': index)) =
(case Index.order of
Index.RowMajor => ((build_range_iterator2 lo up lo' up') [] [] f )
| Index.ColumnMajor => ((build_range_iterator2 (List.rev lo) (List.rev up) (List.rev lo') (List.rev up')) [] [] f ))
| iteri2_range (f: ((index * index) * (index * index)) -> bool)
(RangeSet(shape,set),RangeSet(shape',set')) =
(case Index.order of
Index.RowMajor => (ListPair.all (fn ((lo,up),(lo',up')) =>
(build_range_iterator2 lo up lo' up') [] [] f)
(set,set') )
| Index.ColumnMajor => (ListPair.all (fn ((lo,up),(lo',up')) =>
(build_range_iterator2 (List.rev lo) (List.rev up) (List.rev lo') (List.rev up')) [] [] f)
(set,set') ))
| iteri2_range f (_,_) = raise Range
(* Builds an iterator that applies 'f' sequentially to
all the ranges of contiguous indices (i,j) *)
fun foldi_range f init RangeEmpty = init
| foldi_range (f: ((index * index) * 'a -> 'a)) init (RangeIn(shape,lo: index,up: index)) =
(case Index.order of
Index.RowMajor => ((build_range_fold lo up) [] f init)
| Index.ColumnMajor => ((build_range_fold (List.rev lo) (List.rev up)) [] f init))
| foldi_range (f: ((index * index) * 'a -> 'a)) init (RangeSet(shape,set)) =
(case Index.order of
Index.RowMajor => (List.foldl (fn ((lo,up),init) => ((build_range_fold lo up) [] f init)) init set)
| Index.ColumnMajor => (List.foldl (fn ((lo,up),init) => ((build_range_fold (List.rev lo) (List.rev up)) [] f init)) init set))
end
end
signature SLIDING_RANGE =
sig
structure Index : INDEX
type index = Index.t
type t
exception Range
val fromto : index -> index -> index * index -> t
val fromto' : index -> index -> index * index -> t
val upto : index -> index -> index -> t
val below : index -> index -> index -> t
val first : t -> index
val last : t -> index
val length : t -> int
val stride : t -> index
val offset : t -> int
val ptr : t -> int
val shape : t -> index
val shapes : t -> index list
val inRange : t -> index -> bool
val next : t -> index -> index option
val prev : t -> index -> index option
val shiftr : t -> bool
val reset : t -> unit
val iteri : (index -> bool) -> t -> bool
val iteri2 : (index * index -> bool) -> (t * t) -> bool
val iteri3 : (index * index * index -> bool) -> (t * t * t) -> bool
val foldi_range : (((index * index) * 'a) -> 'a) -> 'a -> t -> 'a