-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
operators.jl
1418 lines (1102 loc) · 34.1 KB
/
operators.jl
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
# This file is a part of Julia. License is MIT: https://julialang.org/license
## types ##
"""
<:(T1, T2)
Subtype operator: returns `true` if and only if all values of type `T1` are
also of type `T2`.
# Examples
```jldoctest
julia> Float64 <: AbstractFloat
true
julia> Vector{Int} <: AbstractArray
true
julia> Matrix{Float64} <: Matrix{AbstractFloat}
false
```
"""
(<:)
"""
>:(T1, T2)
Supertype operator, equivalent to `T2 <: T1`.
"""
(>:)(@nospecialize(a), @nospecialize(b)) = (b <: a)
"""
supertype(T::DataType)
Return the supertype of DataType `T`.
# Examples
```jldoctest
julia> supertype(Int32)
Signed
```
"""
function supertype(T::DataType)
@_pure_meta
T.super
end
function supertype(T::UnionAll)
@_pure_meta
UnionAll(T.var, supertype(T.body))
end
## generic comparison ##
"""
==(x, y)
Generic equality operator. Falls back to [`===`](@ref).
Should be implemented for all types with a notion of equality, based on the abstract value
that an instance represents. For example, all numeric types are compared by numeric value,
ignoring type. Strings are compared as sequences of characters, ignoring encoding.
For collections, `==` is generally called recursively on all contents,
though other properties (like the shape for arrays) may also be taken into account.
This operator follows IEEE semantics for floating-point numbers: `0.0 == -0.0` and
`NaN != NaN`.
The result is of type `Bool`, except when one of the operands is [`missing`](@ref),
in which case `missing` is returned
([three-valued logic](https://en.wikipedia.org/wiki/Three-valued_logic)).
For collections, `missing` is returned if at least one of the operands contains
a `missing` value and all non-missing values are equal.
Use [`isequal`](@ref) or [`===`](@ref) to always get a `Bool` result.
# Implementation
New numeric types should implement this function for two arguments of the new type, and
handle comparison to other types via promotion rules where possible.
[`isequal`](@ref) falls back to `==`, so new methods of `==` will be used by the
[`Dict`](@ref) type to compare keys. If your type will be used as a dictionary key, it
should therefore also implement [`hash`](@ref).
If some type defines `==`, [`isequal`](@ref), and [`isless`](@ref) then it should
also implement [`<`](@ref) to ensure consistency of comparisons.
"""
==
"""
isequal(x, y)
Similar to [`==`](@ref), except for the treatment of floating point numbers
and of missing values. `isequal` treats all floating-point `NaN` values as equal
to each other, treats `-0.0` as unequal to `0.0`, and [`missing`](@ref) as equal
to `missing`. Always returns a `Bool` value.
`isequal` is an equivalence relation - it is reflexive (`===` implies `isequal`), symmetric
(`isequal(a, b)` implies `isequal(b, a)`) and transitive (`isequal(a, b)` and
`isequal(b, c)` implies `isequal(a, c)`).
# Implementation
The default implementation of `isequal` calls `==`, so a type that does not involve
floating-point values generally only needs to define `==`.
`isequal` is the comparison function used by hash tables (`Dict`). `isequal(x,y)` must imply
that `hash(x) == hash(y)`.
This typically means that types for which a custom `==` or `isequal` method exists must
implement a corresponding [`hash`](@ref) method (and vice versa). Collections typically
implement `isequal` by calling `isequal` recursively on all contents.
Furthermore, `isequal` is linked with [`isless`](@ref), and they work together to
define a fixed total ordering, where exactly one of `isequal(x, y)`, `isless(x, y)`, or
`isless(y, x)` must be `true` (and the other two `false`).
Scalar types generally do not need to implement `isequal` separate from `==`, unless they
represent floating-point numbers amenable to a more efficient implementation than that
provided as a generic fallback (based on `isnan`, `signbit`, and `==`).
# Examples
```jldoctest
julia> isequal([1., NaN], [1., NaN])
true
julia> [1., NaN] == [1., NaN]
false
julia> 0.0 == -0.0
true
julia> isequal(0.0, -0.0)
false
julia> missing == missing
missing
julia> isequal(missing, missing)
true
```
"""
isequal(x, y) = (x == y)::Bool # all `missing` cases are handled in missing.jl
signequal(x, y) = signbit(x)::Bool == signbit(y)::Bool
signless(x, y) = signbit(x)::Bool & !signbit(y)::Bool
isequal(x::AbstractFloat, y::AbstractFloat) = (isnan(x) & isnan(y)) | signequal(x, y) & (x == y)::Bool
isequal(x::Real, y::AbstractFloat) = (isnan(x) & isnan(y)) | signequal(x, y) & (x == y)::Bool
isequal(x::AbstractFloat, y::Real ) = (isnan(x) & isnan(y)) | signequal(x, y) & (x == y)::Bool
"""
isless(x, y)
Test whether `x` is less than `y`, according to a fixed total order (defined together with
[`isequal`](@ref)). `isless` is not defined on all pairs of values `(x, y)`. However, if it
is defined, it is expected to satisfy the following:
- If `isless(x, y)` is defined, then so is `isless(y, x)` and `isequal(x, y)`,
and exactly one of those three yields `true`.
- The relation defined by `isless` is transitive, i.e.,
`isless(x, y) && isless(y, z)` implies `isless(x, z)`.
Values that are normally unordered, such as `NaN`,
are ordered after regular values.
[`missing`](@ref) values are ordered last.
This is the default comparison used by [`sort`](@ref).
# Implementation
Non-numeric types with a total order should implement this function.
Numeric types only need to implement it if they have special values such as `NaN`.
Types with a partial order should implement [`<`](@ref).
See the documentation on [Alternate orderings](@ref) for how to define alternate
ordering methods that can be used in sorting and related functions.
# Examples
```jldoctest
julia> isless(1, 3)
true
julia> isless("Red", "Blue")
false
```
"""
function isless end
isless(x::AbstractFloat, y::AbstractFloat) = (!isnan(x) & (isnan(y) | signless(x, y))) | (x < y)
isless(x::Real, y::AbstractFloat) = (!isnan(x) & (isnan(y) | signless(x, y))) | (x < y)
isless(x::AbstractFloat, y::Real ) = (!isnan(x) & (isnan(y) | signless(x, y))) | (x < y)
"""
isgreater(x, y)
Not the inverse of `isless`! Test whether `x` is greater than `y`, according to
a fixed total order compatible with `min`.
Defined with `isless`, this function is usually `isless(y, x)`, but `NaN` and
[`missing`](@ref) are ordered as smaller than any ordinary value with `missing`
smaller than `NaN`.
So `isless` defines an ascending total order with `NaN` and `missing` as the
largest values and `isgreater` defines a descending total order with `NaN` and
`missing` as the smallest values.
!!! note
Like `min`, `isgreater` orders containers (tuples, vectors, etc)
lexicographically with `isless(y, x)` rather than recursively with itself:
```jldoctest
julia> Base.isgreater(1, NaN) # 1 is greater than NaN
true
julia> Base.isgreater((1,), (NaN,)) # But (1,) is not greater than (NaN,)
false
julia> sort([1, 2, 3, NaN]; lt=Base.isgreater)
4-element Vector{Float64}:
3.0
2.0
1.0
NaN
julia> sort(tuple.([1, 2, 3, NaN]); lt=Base.isgreater)
4-element Vector{Tuple{Float64}}:
(NaN,)
(3.0,)
(2.0,)
(1.0,)
```
# Implementation
This is unexported. Types should not usually implement this function. Instead, implement `isless`.
"""
isgreater(x, y) = isunordered(x) || isunordered(y) ? isless(x, y) : isless(y, x)
"""
isunordered(x)
Return true if `x` is a value that is not normally orderable, such as `NaN` or `missing`.
!!! compat "Julia 1.7"
This function requires Julia 1.7 or later.
"""
isunordered(x) = false
isunordered(x::AbstractFloat) = isnan(x)
isunordered(x::Missing) = true
function ==(T::Type, S::Type)
@_pure_meta
return ccall(:jl_types_equal, Cint, (Any, Any), T, S) != 0
end
function !=(T::Type, S::Type)
@_pure_meta
return !(T == S)
end
==(T::TypeVar, S::Type) = false
==(T::Type, S::TypeVar) = false
## comparison fallbacks ##
"""
!=(x, y)
≠(x,y)
Not-equals comparison operator. Always gives the opposite answer as [`==`](@ref).
# Implementation
New types should generally not implement this, and rely on the fallback definition
`!=(x,y) = !(x==y)` instead.
# Examples
```jldoctest
julia> 3 != 2
true
julia> "foo" ≠ "foo"
false
```
"""
!=(x, y) = !(x == y)
const ≠ = !=
"""
===(x,y) -> Bool
≡(x,y) -> Bool
Determine whether `x` and `y` are identical, in the sense that no program could distinguish
them. First the types of `x` and `y` are compared. If those are identical, mutable objects
are compared by address in memory and immutable objects (such as numbers) are compared by
contents at the bit level. This function is sometimes called "egal".
It always returns a `Bool` value.
# Examples
```jldoctest
julia> a = [1, 2]; b = [1, 2];
julia> a == b
true
julia> a === b
false
julia> a === a
true
```
"""
===
const ≡ = ===
"""
!==(x, y)
≢(x,y)
Always gives the opposite answer as [`===`](@ref).
# Examples
```jldoctest
julia> a = [1, 2]; b = [1, 2];
julia> a ≢ b
true
julia> a ≢ a
false
```
"""
!==(@nospecialize(x), @nospecialize(y)) = !(x === y)
const ≢ = !==
"""
<(x, y)
Less-than comparison operator. Falls back to [`isless`](@ref).
Because of the behavior of floating-point NaN values, this operator implements
a partial order.
# Implementation
New numeric types with a canonical partial order should implement this function for
two arguments of the new type.
Types with a canonical total order should implement [`isless`](@ref) instead.
# Examples
```jldoctest
julia> 'a' < 'b'
true
julia> "abc" < "abd"
true
julia> 5 < 3
false
```
"""
<(x, y) = isless(x, y)
"""
>(x, y)
Greater-than comparison operator. Falls back to `y < x`.
# Implementation
Generally, new types should implement [`<`](@ref) instead of this function,
and rely on the fallback definition `>(x, y) = y < x`.
# Examples
```jldoctest
julia> 'a' > 'b'
false
julia> 7 > 3 > 1
true
julia> "abc" > "abd"
false
julia> 5 > 3
true
```
"""
>(x, y) = y < x
"""
<=(x, y)
≤(x,y)
Less-than-or-equals comparison operator. Falls back to `(x < y) | (x == y)`.
# Examples
```jldoctest
julia> 'a' <= 'b'
true
julia> 7 ≤ 7 ≤ 9
true
julia> "abc" ≤ "abc"
true
julia> 5 <= 3
false
```
"""
<=(x, y) = (x < y) | (x == y)
const ≤ = <=
"""
>=(x, y)
≥(x,y)
Greater-than-or-equals comparison operator. Falls back to `y <= x`.
# Examples
```jldoctest
julia> 'a' >= 'b'
false
julia> 7 ≥ 7 ≥ 3
true
julia> "abc" ≥ "abc"
true
julia> 5 >= 3
true
```
"""
>=(x, y) = (y <= x)
const ≥ = >=
# this definition allows Number types to implement < instead of isless,
# which is more idiomatic:
isless(x::Real, y::Real) = x<y
"""
cmp(x,y)
Return -1, 0, or 1 depending on whether `x` is less than, equal to, or greater than `y`,
respectively. Uses the total order implemented by `isless`.
# Examples
```jldoctest
julia> cmp(1, 2)
-1
julia> cmp(2, 1)
1
julia> cmp(2+im, 3-im)
ERROR: MethodError: no method matching isless(::Complex{Int64}, ::Complex{Int64})
[...]
```
"""
cmp(x, y) = isless(x, y) ? -1 : ifelse(isless(y, x), 1, 0)
"""
cmp(<, x, y)
Return -1, 0, or 1 depending on whether `x` is less than, equal to, or greater than `y`,
respectively. The first argument specifies a less-than comparison function to use.
"""
cmp(<, x, y) = (x < y) ? -1 : ifelse(y < x, 1, 0)
# cmp returns -1, 0, +1 indicating ordering
cmp(x::Integer, y::Integer) = ifelse(isless(x, y), -1, ifelse(isless(y, x), 1, 0))
"""
max(x, y, ...)
Return the maximum of the arguments (with respect to [`isless`](@ref)). See also the [`maximum`](@ref) function
to take the maximum element from a collection.
# Examples
```jldoctest
julia> max(2, 5, 1)
5
```
"""
max(x, y) = ifelse(isless(y, x), x, y)
"""
min(x, y, ...)
Return the minimum of the arguments (with respect to [`isless`](@ref)). See also the [`minimum`](@ref) function
to take the minimum element from a collection.
# Examples
```jldoctest
julia> min(2, 5, 1)
1
```
"""
min(x,y) = ifelse(isless(y, x), y, x)
"""
minmax(x, y)
Return `(min(x,y), max(x,y))`.
See also [`extrema`](@ref) that returns `(minimum(x), maximum(x))`.
# Examples
```jldoctest
julia> minmax('c','b')
('b', 'c')
```
"""
minmax(x,y) = isless(y, x) ? (y, x) : (x, y)
"""
extrema(itr) -> Tuple
Compute both the minimum and maximum element in a single pass, and return them as a 2-tuple.
# Examples
```jldoctest
julia> extrema(2:10)
(2, 10)
julia> extrema([9,pi,4.5])
(3.141592653589793, 9.0)
```
"""
extrema(itr) = _extrema_itr(identity, itr)
"""
extrema(f, itr) -> Tuple
Compute both the minimum and maximum of `f` applied to each element in `itr` and return
them as a 2-tuple. Only one pass is made over `itr`.
!!! compat "Julia 1.2"
This method requires Julia 1.2 or later.
# Examples
```jldoctest
julia> extrema(sin, 0:π)
(0.0, 0.9092974268256817)
```
"""
extrema(f, itr) = _extrema_itr(f, itr)
function _extrema_itr(f, itr)
y = iterate(itr)
y === nothing && throw(ArgumentError("collection must be non-empty"))
(v, s) = y
vmin = vmax = f(v)
while true
y = iterate(itr, s)
y === nothing && break
(x, s) = y
fx = f(x)
vmax = max(fx, vmax)
vmin = min(fx, vmin)
end
return (vmin, vmax)
end
extrema(x::Real) = (x, x)
extrema(f, x::Real) = (y = f(x); (y, y))
## definitions providing basic traits of arithmetic operators ##
"""
identity(x)
The identity function. Returns its argument.
See also: [`one`](@ref), [`oneunit`](@ref), and [`LinearAlgebra`](@ref man-linalg)'s `I`.
# Examples
```jldoctest
julia> identity("Well, what did you expect?")
"Well, what did you expect?"
```
"""
identity(x) = x
+(x::Number) = x
*(x::Number) = x
(&)(x::Integer) = x
(|)(x::Integer) = x
xor(x::Integer) = x
const ⊻ = xor
const ⊼ = nand
const ⊽ = nor
# foldl for argument lists. expand fully up to a point, then
# switch to a loop. this allows small cases like `a+b+c+d` to be managed
# efficiently, without a major slowdown for `+(x...)` when `x` is big.
# n.b.: keep this method count small, so it can be inferred without hitting the
# method count limit in inference
afoldl(op, a) = a
function afoldl(op, a, bs...)
l = length(bs)
i = 0; y = a; l == i && return y
#@nexprs 31 i -> (y = op(y, bs[i]); l == i && return y)
i = 1; y = op(y, bs[i]); l == i && return y
i = 2; y = op(y, bs[i]); l == i && return y
i = 3; y = op(y, bs[i]); l == i && return y
i = 4; y = op(y, bs[i]); l == i && return y
i = 5; y = op(y, bs[i]); l == i && return y
i = 6; y = op(y, bs[i]); l == i && return y
i = 7; y = op(y, bs[i]); l == i && return y
i = 8; y = op(y, bs[i]); l == i && return y
i = 9; y = op(y, bs[i]); l == i && return y
i = 10; y = op(y, bs[i]); l == i && return y
i = 11; y = op(y, bs[i]); l == i && return y
i = 12; y = op(y, bs[i]); l == i && return y
i = 13; y = op(y, bs[i]); l == i && return y
i = 14; y = op(y, bs[i]); l == i && return y
i = 15; y = op(y, bs[i]); l == i && return y
i = 16; y = op(y, bs[i]); l == i && return y
i = 17; y = op(y, bs[i]); l == i && return y
i = 18; y = op(y, bs[i]); l == i && return y
i = 19; y = op(y, bs[i]); l == i && return y
i = 20; y = op(y, bs[i]); l == i && return y
i = 21; y = op(y, bs[i]); l == i && return y
i = 22; y = op(y, bs[i]); l == i && return y
i = 23; y = op(y, bs[i]); l == i && return y
i = 24; y = op(y, bs[i]); l == i && return y
i = 25; y = op(y, bs[i]); l == i && return y
i = 26; y = op(y, bs[i]); l == i && return y
i = 27; y = op(y, bs[i]); l == i && return y
i = 28; y = op(y, bs[i]); l == i && return y
i = 29; y = op(y, bs[i]); l == i && return y
i = 30; y = op(y, bs[i]); l == i && return y
i = 31; y = op(y, bs[i]); l == i && return y
for i in (i + 1):l
y = op(y, bs[i])
end
return y
end
typeof(afoldl).name.mt.max_args = 34
for op in (:+, :*, :&, :|, :xor, :min, :max, :kron)
@eval begin
# note: these definitions must not cause a dispatch loop when +(a,b) is
# not defined, and must only try to call 2-argument definitions, so
# that defining +(a,b) is sufficient for full functionality.
($op)(a, b, c, xs...) = (@inline; afoldl($op, ($op)(($op)(a,b),c), xs...))
# a further concern is that it's easy for a type like (Int,Int...)
# to match many definitions, so we need to keep the number of
# definitions down to avoid losing type information.
end
end
function kron! end
const var"'" = adjoint
"""
\\(x, y)
Left division operator: multiplication of `y` by the inverse of `x` on the left. Gives
floating-point results for integer arguments.
# Examples
```jldoctest
julia> 3 \\ 6
2.0
julia> inv(3) * 6
2.0
julia> A = [4 3; 2 1]; x = [5, 6];
julia> A \\ x
2-element Vector{Float64}:
6.5
-7.0
julia> inv(A) * x
2-element Vector{Float64}:
6.5
-7.0
```
"""
\(x,y) = adjoint(adjoint(y)/adjoint(x))
# Core <<, >>, and >>> take either Int or UInt as second arg. Signed shift
# counts can shift in either direction, and are translated here to unsigned
# counts. Integer datatypes only need to implement the unsigned version.
"""
<<(x, n)
Left bit shift operator, `x << n`. For `n >= 0`, the result is `x` shifted left
by `n` bits, filling with `0`s. This is equivalent to `x * 2^n`. For `n < 0`,
this is equivalent to `x >> -n`.
# Examples
```jldoctest
julia> Int8(3) << 2
12
julia> bitstring(Int8(3))
"00000011"
julia> bitstring(Int8(12))
"00001100"
```
See also [`>>`](@ref), [`>>>`](@ref), [`exp2`](@ref), [`ldexp`](@ref).
"""
function <<(x::Integer, c::Integer)
@inline
typemin(Int) <= c <= typemax(Int) && return x << (c % Int)
(x >= 0 || c >= 0) && return zero(x) << 0 # for type stability
oftype(x, -1)
end
function <<(x::Integer, c::Unsigned)
@inline
if c isa UInt
throw(MethodError(<<, (x, c)))
end
c <= typemax(UInt) ? x << (c % UInt) : zero(x) << UInt(0)
end
<<(x::Integer, c::Int) = c >= 0 ? x << unsigned(c) : x >> unsigned(-c)
"""
>>(x, n)
Right bit shift operator, `x >> n`. For `n >= 0`, the result is `x` shifted
right by `n` bits, where `n >= 0`, filling with `0`s if `x >= 0`, `1`s if `x <
0`, preserving the sign of `x`. This is equivalent to `fld(x, 2^n)`. For `n <
0`, this is equivalent to `x << -n`.
# Examples
```jldoctest
julia> Int8(13) >> 2
3
julia> bitstring(Int8(13))
"00001101"
julia> bitstring(Int8(3))
"00000011"
julia> Int8(-14) >> 2
-4
julia> bitstring(Int8(-14))
"11110010"
julia> bitstring(Int8(-4))
"11111100"
```
See also [`>>>`](@ref), [`<<`](@ref).
"""
function >>(x::Integer, c::Integer)
@inline
if c isa UInt
throw(MethodError(>>, (x, c)))
end
typemin(Int) <= c <= typemax(Int) && return x >> (c % Int)
(x >= 0 || c < 0) && return zero(x) >> 0
oftype(x, -1)
end
>>(x::Integer, c::Int) = c >= 0 ? x >> unsigned(c) : x << unsigned(-c)
"""
>>>(x, n)
Unsigned right bit shift operator, `x >>> n`. For `n >= 0`, the result is `x`
shifted right by `n` bits, where `n >= 0`, filling with `0`s. For `n < 0`, this
is equivalent to `x << -n`.
For [`Unsigned`](@ref) integer types, this is equivalent to [`>>`](@ref). For
[`Signed`](@ref) integer types, this is equivalent to `signed(unsigned(x) >> n)`.
# Examples
```jldoctest
julia> Int8(-14) >>> 2
60
julia> bitstring(Int8(-14))
"11110010"
julia> bitstring(Int8(60))
"00111100"
```
[`BigInt`](@ref)s are treated as if having infinite size, so no filling is required and this
is equivalent to [`>>`](@ref).
See also [`>>`](@ref), [`<<`](@ref).
"""
function >>>(x::Integer, c::Integer)
@inline
typemin(Int) <= c <= typemax(Int) ? x >>> (c % Int) : zero(x) >>> 0
end
function >>>(x::Integer, c::Unsigned)
@inline
if c isa UInt
throw(MethodError(>>>, (x, c)))
end
c <= typemax(UInt) ? x >>> (c % UInt) : zero(x) >>> 0
end
>>>(x::Integer, c::Int) = c >= 0 ? x >>> unsigned(c) : x << unsigned(-c)
# operator alias
"""
rem(x, y)
%(x, y)
Remainder from Euclidean division, returning a value of the same sign as `x`, and smaller in
magnitude than `y`. This value is always exact.
See also: [`div`](@ref), [`mod`](@ref), [`mod1`](@ref), [`divrem`](@ref).
# Examples
```jldoctest
julia> x = 15; y = 4;
julia> x % y
3
julia> x == div(x, y) * y + rem(x, y)
true
julia> rem.(-5:5, 3)'
1×11 adjoint(::Vector{Int64}) with eltype Int64:
-2 -1 0 -2 -1 0 1 2 0 1 2
```
"""
rem
const % = rem
"""
div(x, y)
÷(x, y)
The quotient from Euclidean (integer) division. Generally equivalent
to a mathematical operation x/y without a fractional part.
See also: [`cld`](@ref), [`fld`](@ref), [`rem`](@ref), [`divrem`](@ref).
# Examples
```jldoctest
julia> 9 ÷ 4
2
julia> -5 ÷ 3
-1
julia> 5.0 ÷ 2
2.0
julia> div.(-5:5, 3)'
1×11 adjoint(::Vector{Int64}) with eltype Int64:
-1 -1 -1 0 0 0 0 0 1 1 1
```
"""
div
const ÷ = div
"""
mod1(x, y)
Modulus after flooring division, returning a value `r` such that `mod(r, y) == mod(x, y)`
in the range ``(0, y]`` for positive `y` and in the range ``[y,0)`` for negative `y`.
With integer arguments and positive `y`, this is equal to `mod(x, 1:y)`, and hence natural
for 1-based indexing. By comparison, `mod(x, y) == mod(x, 0:y-1)` is natural for computations with
offsets or strides.
See also [`mod`](@ref), [`fld1`](@ref), [`fldmod1`](@ref).
# Examples
```jldoctest
julia> mod1(4, 2)
2
julia> mod1.(-5:5, 3)'
1×11 adjoint(::Vector{Int64}) with eltype Int64:
1 2 3 1 2 3 1 2 3 1 2
julia> mod1.([-0.1, 0, 0.1, 1, 2, 2.9, 3, 3.1]', 3)
1×8 Matrix{Float64}:
2.9 3.0 0.1 1.0 2.0 2.9 3.0 0.1
```
"""
mod1(x::T, y::T) where {T<:Real} = (m = mod(x, y); ifelse(m == 0, y, m))
"""
fld1(x, y)
Flooring division, returning a value consistent with `mod1(x,y)`
See also [`mod1`](@ref), [`fldmod1`](@ref).
# Examples
```jldoctest
julia> x = 15; y = 4;
julia> fld1(x, y)
4
julia> x == fld(x, y) * y + mod(x, y)
true
julia> x == (fld1(x, y) - 1) * y + mod1(x, y)
true
```
"""
fld1(x::T, y::T) where {T<:Real} = (m = mod1(x, y); fld(x + y - m, y))
function fld1(x::T, y::T) where T<:Integer
d = div(x, y)
return d + (!signbit(x ⊻ y) & (d * y != x))
end
"""
fldmod1(x, y)
Return `(fld1(x,y), mod1(x,y))`.
See also [`fld1`](@ref), [`mod1`](@ref).
"""
fldmod1(x, y) = (fld1(x, y), mod1(x, y))
"""
widen(x)
If `x` is a type, return a "larger" type, defined so that arithmetic operations
`+` and `-` are guaranteed not to overflow nor lose precision for any combination
of values that type `x` can hold.
For fixed-size integer types less than 128 bits, `widen` will return a type with
twice the number of bits.
If `x` is a value, it is converted to `widen(typeof(x))`.
# Examples
```jldoctest
julia> widen(Int32)
Int64
julia> widen(1.5f0)
1.5
```
"""
widen(x::T) where {T} = convert(widen(T), x)
widen(x::Type{T}) where {T} = throw(MethodError(widen, (T,)))
# function pipelining
"""
|>(x, f)
Applies a function to the preceding argument. This allows for easy function chaining.
# Examples
```jldoctest
julia> [1:5;] |> x->x.^2 |> sum |> inv
0.01818181818181818
```
"""
|>(x, f) = f(x)
"""
f = Returns(value)
Create a callable `f` such that `f(args...; kw...) === value` holds.
# Examples
```jldoctest
julia> f = Returns(42);
julia> f(1)
42
julia> f("hello", x=32)
42
julia> f.value
42
```
!!! compat "Julia 1.7"
`Returns` requires at least Julia 1.7.
"""
struct Returns{V} <: Function
value::V
Returns{V}(value) where {V} = new{V}(value)
Returns(value) = new{Core.Typeof(value)}(value)
end
(obj::Returns)(args...; kw...) = obj.value
function show(io::IO, obj::Returns)
show(io, typeof(obj))
print(io, "(")
show(io, obj.value)
print(io, ")")
end
# function composition
"""
f ∘ g