/
comparison.d
2045 lines (1779 loc) · 60.6 KB
/
comparison.d
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
// Written in the D programming language.
/**
This is a submodule of $(LINK2 std_algorithm.html, std.algorithm).
It contains generic _comparison algorithms.
$(BOOKTABLE Cheat Sheet,
$(TR $(TH Function Name) $(TH Description))
$(T2 among,
Checks if a value is among a set of values, e.g.
$(D if (v.among(1, 2, 3)) // `v` is 1, 2 or 3))
$(T2 castSwitch,
$(D (new A()).castSwitch((A a)=>1,(B b)=>2)) returns $(D 1).)
$(T2 clamp,
$(D clamp(1, 3, 6)) returns $(D 3). $(D clamp(4, 3, 6)) returns $(D 4).)
$(T2 cmp,
$(D cmp("abc", "abcd")) is $(D -1), $(D cmp("abc", "aba")) is $(D 1),
and $(D cmp("abc", "abc")) is $(D 0).)
$(T2 either,
Return first parameter $(D p) that passes an $(D if (p)) test, e.g.
$(D either(0, 42, 43)) returns $(D 42).)
$(T2 equal,
Compares ranges for element-by-element equality, e.g.
$(D equal([1, 2, 3], [1.0, 2.0, 3.0])) returns $(D true).)
$(T2 isPermutation,
$(D isPermutation([1, 2], [2, 1])) returns $(D true).)
$(T2 isSameLength,
$(D isSameLength([1, 2, 3], [4, 5, 6])) returns $(D true).)
$(T2 levenshteinDistance,
$(D levenshteinDistance("kitten", "sitting")) returns $(D 3) by using
the $(LUCKY Levenshtein distance _algorithm).)
$(T2 levenshteinDistanceAndPath,
$(D levenshteinDistanceAndPath("kitten", "sitting")) returns
$(D tuple(3, "snnnsni")) by using the $(LUCKY Levenshtein distance
_algorithm).)
$(T2 max,
$(D max(3, 4, 2)) returns $(D 4).)
$(T2 min,
$(D min(3, 4, 2)) returns $(D 2).)
$(T2 mismatch,
$(D mismatch("oh hi", "ohayo")) returns $(D tuple(" hi", "ayo")).)
$(T2 predSwitch,
$(D 2.predSwitch(1, "one", 2, "two", 3, "three")) returns $(D "two").)
)
Copyright: Andrei Alexandrescu 2008-.
License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(WEB erdani.com, Andrei Alexandrescu)
Source: $(PHOBOSSRC std/algorithm/_comparison.d)
Macros:
T2=$(TR $(TDNW $(LREF $1)) $(TD $+))
*/
module std.algorithm.comparison;
// FIXME
import std.functional; // : unaryFun, binaryFun;
import std.range;
import std.traits;
// FIXME
import std.typecons; // : tuple, Tuple, Flag;
import std.meta : allSatisfy;
/**
Find $(D value) _among $(D values), returning the 1-based index
of the first matching value in $(D values), or $(D 0) if $(D value)
is not _among $(D values). The predicate $(D pred) is used to
compare values, and uses equality by default.
Params:
pred = The predicate used to compare the values.
value = The value to search for.
values = The values to compare the value to.
Returns:
0 if value was not found among the values, otherwise the index of the
found value plus one is returned.
See_Also:
$(XREF_PACK_NAMED algorithm,searching,find,find) and $(XREF_PACK_NAMED algorithm,searching,canFind, canFind) for finding a value in a
range.
*/
uint among(alias pred = (a, b) => a == b, Value, Values...)
(Value value, Values values)
if (Values.length != 0)
{
foreach (uint i, ref v; values)
{
import std.functional : binaryFun;
if (binaryFun!pred(value, v)) return i + 1;
}
return 0;
}
/// Ditto
template among(values...)
if (isExpressionTuple!values)
{
uint among(Value)(Value value)
if (!is(CommonType!(Value, values) == void))
{
switch (value)
{
foreach (uint i, v; values)
case v:
return i + 1;
default:
return 0;
}
}
}
///
@safe unittest
{
assert(3.among(1, 42, 24, 3, 2));
if (auto pos = "bar".among("foo", "bar", "baz"))
assert(pos == 2);
else
assert(false);
// 42 is larger than 24
assert(42.among!((lhs, rhs) => lhs > rhs)(43, 24, 100) == 2);
}
/**
Alternatively, $(D values) can be passed at compile-time, allowing for a more
efficient search, but one that only supports matching on equality:
*/
@safe unittest
{
assert(3.among!(2, 3, 4));
assert("bar".among!("foo", "bar", "baz") == 2);
}
@safe unittest
{
import std.meta : AliasSeq;
if (auto pos = 3.among(1, 2, 3))
assert(pos == 3);
else
assert(false);
assert(!4.among(1, 2, 3));
auto position = "hello".among("hello", "world");
assert(position);
assert(position == 1);
alias values = AliasSeq!("foo", "bar", "baz");
auto arr = [values];
assert(arr[0 .. "foo".among(values)] == ["foo"]);
assert(arr[0 .. "bar".among(values)] == ["foo", "bar"]);
assert(arr[0 .. "baz".among(values)] == arr);
assert("foobar".among(values) == 0);
if (auto pos = 3.among!(1, 2, 3))
assert(pos == 3);
else
assert(false);
assert(!4.among!(1, 2, 3));
position = "hello".among!("hello", "world");
assert(position);
assert(position == 1);
static assert(!__traits(compiles, "a".among!("a", 42)));
static assert(!__traits(compiles, (Object.init).among!(42, "a")));
}
// Used in castSwitch to find the first choice that overshadows the last choice
// in a tuple.
private template indexOfFirstOvershadowingChoiceOnLast(choices...)
{
alias firstParameterTypes = Parameters!(choices[0]);
alias lastParameterTypes = Parameters!(choices[$ - 1]);
static if (lastParameterTypes.length == 0)
{
// If the last is null-typed choice, check if the first is null-typed.
enum isOvershadowing = firstParameterTypes.length == 0;
}
else static if (firstParameterTypes.length == 1)
{
// If the both first and last are not null-typed, check for overshadowing.
enum isOvershadowing =
is(firstParameterTypes[0] == Object) // Object overshadows all other classes!(this is needed for interfaces)
|| is(lastParameterTypes[0] : firstParameterTypes[0]);
}
else
{
// If the first is null typed and the last is not - the is no overshadowing.
enum isOvershadowing = false;
}
static if (isOvershadowing)
{
enum indexOfFirstOvershadowingChoiceOnLast = 0;
}
else
{
enum indexOfFirstOvershadowingChoiceOnLast =
1 + indexOfFirstOvershadowingChoiceOnLast!(choices[1..$]);
}
}
/**
Executes and returns one of a collection of handlers based on the type of the
switch object.
The first choice that $(D switchObject) can be casted to the type
of argument it accepts will be called with $(D switchObject) casted to that
type, and the value it'll return will be returned by $(D castSwitch).
If a choice's return type is void, the choice must throw an exception, unless
all the choices are void. In that case, castSwitch itself will return void.
Throws: If none of the choice matches, a $(D SwitchError) will be thrown. $(D
SwitchError) will also be thrown if not all the choices are void and a void
choice was executed without throwing anything.
Params:
choices = The $(D choices) needs to be composed of function or delegate
handlers that accept one argument. There can also be a choice that
accepts zero arguments. That choice will be invoked if the $(D
switchObject) is null.
switchObject = the object against which the tests are being made.
Returns:
The value of the selected choice.
Note: $(D castSwitch) can only be used with object types.
*/
auto castSwitch(choices...)(Object switchObject)
{
import core.exception : SwitchError;
// Check to see if all handlers return void.
enum areAllHandlersVoidResult = {
bool result = true;
foreach (index, choice; choices)
{
result &= is(ReturnType!choice == void);
}
return result;
}();
if (switchObject !is null)
{
// Checking for exact matches:
ClassInfo classInfo = typeid(switchObject);
foreach (index, choice; choices)
{
static assert(isCallable!choice,
"A choice handler must be callable");
alias choiceParameterTypes = Parameters!choice;
static assert(choiceParameterTypes.length <= 1,
"A choice handler can not have more than one argument.");
static if (choiceParameterTypes.length == 1)
{
alias CastClass = choiceParameterTypes[0];
static assert(is(CastClass == class) || is(CastClass == interface),
"A choice handler can have only class or interface typed argument.");
// Check for overshadowing:
immutable indexOfOvershadowingChoice =
indexOfFirstOvershadowingChoiceOnLast!(choices[0..index + 1]);
static assert(indexOfOvershadowingChoice == index,
"choice number %d(type %s) is overshadowed by choice number %d(type %s)".format(
index + 1, CastClass.stringof, indexOfOvershadowingChoice + 1,
Parameters!(choices[indexOfOvershadowingChoice])[0].stringof));
if (classInfo == typeid(CastClass))
{
static if(is(ReturnType!(choice) == void))
{
choice(cast(CastClass) switchObject);
static if (areAllHandlersVoidResult)
{
return;
}
else
{
throw new SwitchError("Handlers that return void should throw");
}
}
else
{
return choice(cast(CastClass) switchObject);
}
}
}
}
// Checking for derived matches:
foreach (choice; choices)
{
alias choiceParameterTypes = Parameters!choice;
static if (choiceParameterTypes.length == 1)
{
if (auto castedObject = cast(choiceParameterTypes[0]) switchObject)
{
static if(is(ReturnType!(choice) == void))
{
choice(castedObject);
static if (areAllHandlersVoidResult)
{
return;
}
else
{
throw new SwitchError("Handlers that return void should throw");
}
}
else
{
return choice(castedObject);
}
}
}
}
}
else // If switchObject is null:
{
// Checking for null matches:
foreach (index, choice; choices)
{
static if (Parameters!(choice).length == 0)
{
immutable indexOfOvershadowingChoice =
indexOfFirstOvershadowingChoiceOnLast!(choices[0..index + 1]);
// Check for overshadowing:
static assert(indexOfOvershadowingChoice == index,
"choice number %d(null reference) is overshadowed by choice number %d(null reference)".format(
index + 1, indexOfOvershadowingChoice + 1));
if (switchObject is null)
{
static if(is(ReturnType!(choice) == void))
{
choice();
static if (areAllHandlersVoidResult)
{
return;
}
else
{
throw new SwitchError("Handlers that return void should throw");
}
}
else
{
return choice();
}
}
}
}
}
// In case nothing matched:
throw new SwitchError("Input not matched by any choice");
}
///
unittest
{
import std.algorithm.iteration : map;
import std.format : format;
class A
{
int a;
this(int a) {this.a = a;}
@property int i() { return a; }
}
interface I { }
class B : I { }
Object[] arr = [new A(1), new B(), null];
auto results = arr.map!(castSwitch!(
(A a) => "A with a value of %d".format(a.a),
(I i) => "derived from I",
() => "null reference",
))();
// A is handled directly:
assert(results[0] == "A with a value of 1");
// B has no handler - it is handled by the handler of I:
assert(results[1] == "derived from I");
// null is handled by the null handler:
assert(results[2] == "null reference");
}
/// Using with void handlers:
unittest
{
import std.exception : assertThrown;
class A { }
class B { }
// Void handlers are allowed if they throw:
assertThrown!Exception(
new B().castSwitch!(
(A a) => 1,
(B d) { throw new Exception("B is not allowed!"); }
)()
);
// Void handlers are also allowed if all the handlers are void:
new A().castSwitch!(
(A a) { assert(true); },
(B b) { assert(false); },
)();
}
unittest
{
import core.exception : SwitchError;
import std.exception : assertThrown;
interface I { }
class A : I { }
class B { }
// Nothing matches:
assertThrown!SwitchError((new A()).castSwitch!(
(B b) => 1,
() => 2,
)());
// Choices with multiple arguments are not allowed:
static assert(!__traits(compiles,
(new A()).castSwitch!(
(A a, B b) => 0,
)()));
// Only callable handlers allowed:
static assert(!__traits(compiles,
(new A()).castSwitch!(
1234,
)()));
// Only object arguments allowed:
static assert(!__traits(compiles,
(new A()).castSwitch!(
(int x) => 0,
)()));
// Object overshadows regular classes:
static assert(!__traits(compiles,
(new A()).castSwitch!(
(Object o) => 0,
(A a) => 1,
)()));
// Object overshadows interfaces:
static assert(!__traits(compiles,
(new A()).castSwitch!(
(Object o) => 0,
(I i) => 1,
)()));
// No multiple null handlers allowed:
static assert(!__traits(compiles,
(new A()).castSwitch!(
() => 0,
() => 1,
)()));
// No non-throwing void handlers allowed(when there are non-void handlers):
assertThrown!SwitchError((new A()).castSwitch!(
(A a) {},
(B b) => 2,
)());
// All-void handlers work for the null case:
null.castSwitch!(
(Object o) { assert(false); },
() { assert(true); },
)();
// Throwing void handlers work for the null case:
assertThrown!Exception(null.castSwitch!(
(Object o) => 1,
() { throw new Exception("null"); },
)());
}
/** Clamps a value into the given bounds.
This functions is equivalent to $(D max(lower, min(upper,val))).
Params:
val = The value to _clamp.
lower = The _lower bound of the _clamp.
upper = The _upper bound of the _clamp.
Returns:
Returns $(D val), if it is between $(D lower) and $(D upper).
Otherwise returns the nearest of the two.
*/
auto clamp(T1, T2, T3)(T1 val, T2 lower, T3 upper)
in
{
import std.functional : greaterThan;
assert(!lower.greaterThan(upper));
}
body
{
return max(lower, min(upper, val));
}
///
@safe unittest
{
assert(clamp(2, 1, 3) == 2);
assert(clamp(0, 1, 3) == 1);
assert(clamp(4, 1, 3) == 3);
assert(clamp(1, 1, 1) == 1);
assert(clamp(5, -1, 2u) == 2);
}
@safe unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int a = 1;
short b = 6;
double c = 2;
static assert(is(typeof(clamp(c,a,b)) == double));
assert(clamp(c, a, b) == c);
assert(clamp(a-c, a, b) == a);
assert(clamp(b+c, a, b) == b);
// mixed sign
a = -5;
uint f = 5;
static assert(is(typeof(clamp(f, a, b)) == int));
assert(clamp(f, a, b) == f);
// similar type deduction for (u)long
static assert(is(typeof(clamp(-1L, -2L, 2UL)) == long));
// user-defined types
import std.datetime : Date;
assert(clamp(Date(1982, 1, 4), Date(1012, 12, 21), Date(2012, 12, 21)) == Date(1982, 1, 4));
assert(clamp(Date(1982, 1, 4), Date.min, Date.max) == Date(1982, 1, 4));
// UFCS style
assert(Date(1982, 1, 4).clamp(Date.min, Date.max) == Date(1982, 1, 4));
}
// cmp
/**********************************
Performs three-way lexicographical comparison on two input ranges
according to predicate $(D pred). Iterating $(D r1) and $(D r2) in
lockstep, $(D cmp) compares each element $(D e1) of $(D r1) with the
corresponding element $(D e2) in $(D r2). If one of the ranges has been
finished, $(D cmp) returns a negative value if $(D r1) has fewer
elements than $(D r2), a positive value if $(D r1) has more elements
than $(D r2), and $(D 0) if the ranges have the same number of
elements.
If the ranges are strings, $(D cmp) performs UTF decoding
appropriately and compares the ranges one code point at a time.
Params:
pred = The predicate used for comparison.
r1 = The first range.
r2 = The second range.
Returns:
0 if both ranges compare equal. -1 if the first differing element of $(D
r1) is less than the corresponding element of $(D r2) according to $(D
pred). 1 if the first differing element of $(D r2) is less than the
corresponding element of $(D r1) according to $(D pred).
*/
int cmp(alias pred = "a < b", R1, R2)(R1 r1, R2 r2)
if (isInputRange!R1 && isInputRange!R2 && !(isSomeString!R1 && isSomeString!R2))
{
for (;; r1.popFront(), r2.popFront())
{
if (r1.empty) return -cast(int)!r2.empty;
if (r2.empty) return !r1.empty;
auto a = r1.front, b = r2.front;
if (binaryFun!pred(a, b)) return -1;
if (binaryFun!pred(b, a)) return 1;
}
}
/// ditto
int cmp(alias pred = "a < b", R1, R2)(R1 r1, R2 r2) if (isSomeString!R1 && isSomeString!R2)
{
import core.stdc.string : memcmp;
import std.utf : decode;
static if (is(typeof(pred) : string))
enum isLessThan = pred == "a < b";
else
enum isLessThan = false;
// For speed only
static int threeWay(size_t a, size_t b)
{
static if (size_t.sizeof == int.sizeof && isLessThan)
return a - b;
else
return binaryFun!pred(b, a) ? 1 : binaryFun!pred(a, b) ? -1 : 0;
}
// For speed only
// @@@BUG@@@ overloading should be allowed for nested functions
static int threeWayInt(int a, int b)
{
static if (isLessThan)
return a - b;
else
return binaryFun!pred(b, a) ? 1 : binaryFun!pred(a, b) ? -1 : 0;
}
static if (typeof(r1[0]).sizeof == typeof(r2[0]).sizeof && isLessThan)
{
static if (typeof(r1[0]).sizeof == 1)
{
immutable len = min(r1.length, r2.length);
immutable result = __ctfe ?
{
foreach (i; 0 .. len)
{
if (r1[i] != r2[i])
return threeWayInt(r1[i], r2[i]);
}
return 0;
}()
: () @trusted { return memcmp(r1.ptr, r2.ptr, len); }();
if (result) return result;
}
else
{
auto p1 = r1.ptr, p2 = r2.ptr,
pEnd = p1 + min(r1.length, r2.length);
for (; p1 != pEnd; ++p1, ++p2)
{
if (*p1 != *p2) return threeWayInt(cast(int) *p1, cast(int) *p2);
}
}
return threeWay(r1.length, r2.length);
}
else
{
for (size_t i1, i2;;)
{
if (i1 == r1.length) return threeWay(i2, r2.length);
if (i2 == r2.length) return threeWay(r1.length, i1);
immutable c1 = decode(r1, i1),
c2 = decode(r2, i2);
if (c1 != c2) return threeWayInt(cast(int) c1, cast(int) c2);
}
}
}
///
@safe unittest
{
int result;
result = cmp("abc", "abc");
assert(result == 0);
result = cmp("", "");
assert(result == 0);
result = cmp("abc", "abcd");
assert(result < 0);
result = cmp("abcd", "abc");
assert(result > 0);
result = cmp("abc"d, "abd");
assert(result < 0);
result = cmp("bbc", "abc"w);
assert(result > 0);
result = cmp("aaa", "aaaa"d);
assert(result < 0);
result = cmp("aaaa", "aaa"d);
assert(result > 0);
result = cmp("aaa", "aaa"d);
assert(result == 0);
result = cmp(cast(int[])[], cast(int[])[]);
assert(result == 0);
result = cmp([1, 2, 3], [1, 2, 3]);
assert(result == 0);
result = cmp([1, 3, 2], [1, 2, 3]);
assert(result > 0);
result = cmp([1, 2, 3], [1L, 2, 3, 4]);
assert(result < 0);
result = cmp([1L, 2, 3], [1, 2]);
assert(result > 0);
}
// equal
/**
Compares two ranges for equality, as defined by predicate $(D pred)
(which is $(D ==) by default).
*/
template equal(alias pred = "a == b")
{
/++
This function compares to ranges for equality. The ranges may have
different element types, as long as $(D pred(a, b)) evaluates to $(D bool)
for $(D a) in $(D r1) and $(D b) in $(D r2).
Performs $(BIGOH min(r1.length, r2.length)) evaluations of $(D pred).
Params:
r1 = The first range to be compared.
r2 = The second range to be compared.
Returns:
$(D true) if and only if the two ranges compare equal element
for element, according to binary predicate $(D pred).
See_Also:
$(WEB sgi.com/tech/stl/_equal.html, STL's _equal)
+/
bool equal(Range1, Range2)(Range1 r1, Range2 r2)
if (isInputRange!Range1 && isInputRange!Range2 && is(typeof(binaryFun!pred(r1.front, r2.front))))
{
//Start by detecting default pred and compatible dynamicarray.
static if (is(typeof(pred) == string) && pred == "a == b" &&
isArray!Range1 && isArray!Range2 && is(typeof(r1 == r2)))
{
return r1 == r2;
}
//Try a fast implementation when the ranges have comparable lengths
else static if (hasLength!Range1 && hasLength!Range2 && is(typeof(r1.length == r2.length)))
{
auto len1 = r1.length;
auto len2 = r2.length;
if (len1 != len2) return false; //Short circuit return
//Lengths are the same, so we need to do an actual comparison
//Good news is we can sqeeze out a bit of performance by not checking if r2 is empty
for (; !r1.empty; r1.popFront(), r2.popFront())
{
if (!binaryFun!(pred)(r1.front, r2.front)) return false;
}
return true;
}
else
{
//Generic case, we have to walk both ranges making sure neither is empty
for (; !r1.empty; r1.popFront(), r2.popFront())
{
if (r2.empty) return false;
if (!binaryFun!(pred)(r1.front, r2.front)) return false;
}
return r2.empty;
}
}
}
///
@safe unittest
{
import std.math : approxEqual;
import std.algorithm : equal;
int[] a = [ 1, 2, 4, 3 ];
assert(!equal(a, a[1..$]));
assert(equal(a, a));
// different types
double[] b = [ 1.0, 2, 4, 3];
assert(!equal(a, b[1..$]));
assert(equal(a, b));
// predicated: ensure that two vectors are approximately equal
double[] c = [ 1.005, 2, 4, 3];
assert(equal!approxEqual(b, c));
}
/++
Tip: $(D equal) can itself be used as a predicate to other functions.
This can be very useful when the element type of a range is itself a
range. In particular, $(D equal) can be its own predicate, allowing
range of range (of range...) comparisons.
+/
@safe unittest
{
import std.range : iota, chunks;
import std.algorithm : equal;
assert(equal!(equal!equal)(
[[[0, 1], [2, 3]], [[4, 5], [6, 7]]],
iota(0, 8).chunks(2).chunks(2)
));
}
@safe unittest
{
import std.algorithm.iteration : map;
import std.math : approxEqual;
import std.internal.test.dummyrange : ReferenceForwardRange,
ReferenceInputRange, ReferenceInfiniteForwardRange;
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
// various strings
assert(equal("æøå", "æøå")); //UTF8 vs UTF8
assert(!equal("???", "æøå")); //UTF8 vs UTF8
assert(equal("æøå"w, "æøå"d)); //UTF16 vs UTF32
assert(!equal("???"w, "æøå"d));//UTF16 vs UTF32
assert(equal("æøå"d, "æøå"d)); //UTF32 vs UTF32
assert(!equal("???"d, "æøå"d));//UTF32 vs UTF32
assert(!equal("hello", "world"));
// same strings, but "explicit non default" comparison (to test the non optimized array comparison)
assert( equal!("a == b")("æøå", "æøå")); //UTF8 vs UTF8
assert(!equal!("a == b")("???", "æøå")); //UTF8 vs UTF8
assert( equal!("a == b")("æøå"w, "æøå"d)); //UTF16 vs UTF32
assert(!equal!("a == b")("???"w, "æøå"d));//UTF16 vs UTF32
assert( equal!("a == b")("æøå"d, "æøå"d)); //UTF32 vs UTF32
assert(!equal!("a == b")("???"d, "æøå"d));//UTF32 vs UTF32
assert(!equal!("a == b")("hello", "world"));
//Array of string
assert(equal(["hello", "world"], ["hello", "world"]));
assert(!equal(["hello", "world"], ["hello"]));
assert(!equal(["hello", "world"], ["hello", "Bob!"]));
//Should not compile, because "string == dstring" is illegal
static assert(!is(typeof(equal(["hello", "world"], ["hello"d, "world"d]))));
//However, arrays of non-matching string can be compared using equal!equal. Neat-o!
equal!equal(["hello", "world"], ["hello"d, "world"d]);
//Tests, with more fancy map ranges
int[] a = [ 1, 2, 4, 3 ];
assert(equal([2, 4, 8, 6], map!"a*2"(a)));
double[] b = [ 1.0, 2, 4, 3];
double[] c = [ 1.005, 2, 4, 3];
assert(equal!approxEqual(map!"a*2"(b), map!"a*2"(c)));
assert(!equal([2, 4, 1, 3], map!"a*2"(a)));
assert(!equal([2, 4, 1], map!"a*2"(a)));
assert(!equal!approxEqual(map!"a*3"(b), map!"a*2"(c)));
//Tests with some fancy reference ranges.
ReferenceInputRange!int cir = new ReferenceInputRange!int([1, 2, 4, 3]);
ReferenceForwardRange!int cfr = new ReferenceForwardRange!int([1, 2, 4, 3]);
assert(equal(cir, a));
cir = new ReferenceInputRange!int([1, 2, 4, 3]);
assert(equal(cir, cfr.save));
assert(equal(cfr.save, cfr.save));
cir = new ReferenceInputRange!int([1, 2, 8, 1]);
assert(!equal(cir, cfr));
//Test with an infinte range
ReferenceInfiniteForwardRange!int ifr = new ReferenceInfiniteForwardRange!int;
assert(!equal(a, ifr));
}
// MaxType
private template MaxType(T...)
if (T.length >= 1)
{
static if (T.length == 1)
{
alias MaxType = T[0];
}
else static if (T.length == 2)
{
static if (!is(typeof(T[0].min)))
alias MaxType = CommonType!T;
else static if (T[1].max > T[0].max)
alias MaxType = T[1];
else
alias MaxType = T[0];
}
else
{
alias MaxType = MaxType!(MaxType!(T[0 .. ($+1)/2]), MaxType!(T[($+1)/2 .. $]));
}
}
// levenshteinDistance
/**
Encodes $(WEB realityinteractive.com/rgrzywinski/archives/000249.html,
edit operations) necessary to transform one sequence into
another. Given sequences $(D s) (source) and $(D t) (target), a
sequence of $(D EditOp) encodes the steps that need to be taken to
convert $(D s) into $(D t). For example, if $(D s = "cat") and $(D
"cars"), the minimal sequence that transforms $(D s) into $(D t) is:
skip two characters, replace 't' with 'r', and insert an 's'. Working
with edit operations is useful in applications such as spell-checkers
(to find the closest word to a given misspelled word), approximate
searches, diff-style programs that compute the difference between
files, efficient encoding of patches, DNA sequence analysis, and
plagiarism detection.
*/
enum EditOp : char
{
/** Current items are equal; no editing is necessary. */
none = 'n',
/** Substitute current item in target with current item in source. */
substitute = 's',
/** Insert current item from the source into the target. */
insert = 'i',
/** Remove current item from the target. */
remove = 'r'
}
private struct Levenshtein(Range, alias equals, CostType = size_t)
{
EditOp[] path()
{
import std.algorithm.mutation : reverse;
EditOp[] result;
size_t i = rows - 1, j = cols - 1;
// restore the path
while (i || j) {
auto cIns = j == 0 ? CostType.max : matrix(i,j - 1);
auto cDel = i == 0 ? CostType.max : matrix(i - 1,j);
auto cSub = i == 0 || j == 0
? CostType.max
: matrix(i - 1,j - 1);
switch (min_index(cSub, cIns, cDel)) {
case 0:
result ~= matrix(i - 1,j - 1) == matrix(i,j)
? EditOp.none
: EditOp.substitute;
--i;
--j;
break;
case 1:
result ~= EditOp.insert;
--j;
break;
default:
result ~= EditOp.remove;
--i;
break;
}
}
reverse(result);
return result;
}
~this() {
FreeMatrix();
}
private:
CostType _deletionIncrement = 1,
_insertionIncrement = 1,
_substitutionIncrement = 1;
CostType[] _matrix;
size_t rows, cols;
// Treat _matrix as a rectangular array
ref CostType matrix(size_t row, size_t col) { return _matrix[row * cols + col]; }
void AllocMatrix(size_t r, size_t c) @trusted {
rows = r;
cols = c;
if (_matrix.length < r * c) {
import core.stdc.stdlib : realloc;
import core.exception : onOutOfMemoryError;
auto m = cast(CostType *)realloc(_matrix.ptr, r * c * _matrix[0].sizeof);
if (!m)
onOutOfMemoryError();
_matrix = m[0 .. r * c];
InitMatrix();
}
}
void FreeMatrix() @trusted {
import core.stdc.stdlib : free;
free(_matrix.ptr);
_matrix = null;
}
void InitMatrix() {
foreach (r; 0 .. rows)
matrix(r,0) = r * _deletionIncrement;
foreach (c; 0 .. cols)
matrix(0,c) = c * _insertionIncrement;
}
static uint min_index(CostType i0, CostType i1, CostType i2)
{
if (i0 <= i1)