forked from JuliaLang/julia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bool.jl
112 lines (85 loc) · 2.35 KB
/
bool.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
# This file is a part of Julia. License is MIT: https://julialang.org/license
# promote Bool to any other numeric type
promote_rule(::Type{Bool}, ::Type{T}) where {T<:Number} = T
typemin(::Type{Bool}) = false
typemax(::Type{Bool}) = true
## boolean operations ##
"""
!(x)
Boolean not. Implements [three-valued logic](https://en.wikipedia.org/wiki/Three-valued_logic),
returning [`missing`](@ref) if `x` is `missing`.
# Examples
```jldoctest
julia> !true
false
julia> !false
true
julia> !missing
missing
julia> .![true false true]
1×3 BitMatrix:
0 1 0
```
"""
!(x::Bool) = not_int(x)
(~)(x::Bool) = !x
(&)(x::Bool, y::Bool) = and_int(x, y)
(|)(x::Bool, y::Bool) = or_int(x, y)
"""
xor(x, y)
⊻(x, y)
Bitwise exclusive or of `x` and `y`. Implements
[three-valued logic](https://en.wikipedia.org/wiki/Three-valued_logic),
returning [`missing`](@ref) if one of the arguments is `missing`.
The infix operation `a ⊻ b` is a synonym for `xor(a,b)`, and
`⊻` can be typed by tab-completing `\\xor` or `\\veebar` in the Julia REPL.
# Examples
```jldoctest
julia> xor(true, false)
true
julia> xor(true, true)
false
julia> xor(true, missing)
missing
julia> false ⊻ false
false
julia> [true; true; false] .⊻ [true; false; false]
3-element BitVector:
0
1
0
```
"""
xor(x::Bool, y::Bool) = (x != y)
>>(x::Bool, c::UInt) = Int(x) >> c
<<(x::Bool, c::UInt) = Int(x) << c
>>>(x::Bool, c::UInt) = Int(x) >>> c
signbit(x::Bool) = false
sign(x::Bool) = x
abs(x::Bool) = x
abs2(x::Bool) = x
iszero(x::Bool) = !x
isone(x::Bool) = x
<(x::Bool, y::Bool) = y&!x
<=(x::Bool, y::Bool) = y|!x
## do arithmetic as Int ##
+(x::Bool) = Int(x)
-(x::Bool) = -Int(x)
+(x::Bool, y::Bool) = Int(x) + Int(y)
-(x::Bool, y::Bool) = Int(x) - Int(y)
*(x::Bool, y::Bool) = x & y
^(x::Bool, y::Bool) = x | !y
^(x::Integer, y::Bool) = ifelse(y, x, one(x))
# preserve -0.0 in `false + -0.0`
function +(x::Bool, y::T)::promote_type(Bool,T) where T<:AbstractFloat
return ifelse(x, oneunit(y) + y, y)
end
+(y::AbstractFloat, x::Bool) = x + y
# make `false` a "strong zero": false*NaN == 0.0
function *(x::Bool, y::T)::promote_type(Bool,T) where T<:AbstractFloat
return ifelse(x, y, copysign(zero(y), y))
end
*(y::AbstractFloat, x::Bool) = x * y
div(x::Bool, y::Bool) = y ? x : throw(DivideError())
rem(x::Bool, y::Bool) = y ? false : throw(DivideError())
mod(x::Bool, y::Bool) = rem(x,y)