布尔类型 #
一、布尔值基础 #
1.1 布尔类型 #
Julia的布尔类型是Bool,只有两个值:
julia
true
false
typeof(true)
typeof(false)
1.2 布尔值是整数 #
在Julia中,Bool是Integer的子类型:
julia
true isa Integer
false isa Integer
Int(true)
Int(false)
true + true
true * 5
1.3 布尔值比较 #
julia
true == 1
false == 0
true === 1
二、比较运算 #
2.1 相等比较 #
julia
1 == 1
1 == 2
1 != 2
"hello" == "hello"
[1, 2] == [1, 2]
2.2 大小比较 #
julia
1 < 2
2 > 1
1 <= 1
1 >= 1
"a" < "b"
2.3 链式比较 #
Julia支持链式比较:
julia
1 < 2 < 3
1 < 2 > 1
1 < 3 == 3
1 < 2 < 3 < 4
2.4 特殊比较 #
julia
NaN == NaN
NaN != NaN
isequal(NaN, NaN)
ismissing(missing)
missing === missing
三、逻辑运算 #
3.1 逻辑非 #
julia
!true
!false
!!true
3.2 逻辑与 #
julia
true && true
true && false
false && true
false && false
3.3 逻辑或 #
julia
true || true
true || false
false || true
false || false
3.4 位运算 #
julia
~true
true & false
true | false
true ⊻ false
四、短路求值 #
4.1 && 短路 #
julia
true && println("This prints")
false && println("This doesn't print")
function safe_divide(a, b)
b != 0 && a / b
end
4.2 || 短路 #
julia
true || println("This doesn't print")
false || println("This prints")
function get_value(dict, key, default)
haskey(dict, key) || return default
dict[key]
end
4.3 条件执行 #
julia
x = 5
x > 0 && println("Positive")
x < 0 || println("Non-negative")
五、真假值 #
5.1 布尔上下文 #
在Julia中,只有Bool类型可以直接用于条件判断:
julia
if true
println("True")
end
5.2 转换为布尔值 #
julia
Bool(1)
Bool(0)
Bool(0.0)
Bool(1.0)
5.3 空值判断 #
julia
x = nothing
x === nothing
isnothing(x)
5.4 空集合判断 #
julia
isempty([])
isempty([1, 2, 3])
isempty("")
isempty("Hello")
六、三元运算符 #
6.1 基本语法 #
julia
condition ? value_if_true : value_if_false
x = 5
x > 0 ? "Positive" : "Non-positive"
6.2 嵌套三元 #
julia
x = 0
x > 0 ? "Positive" : x < 0 ? "Negative" : "Zero"
6.3 与if-else对比 #
julia
x = 5
result = x > 0 ? "Positive" : "Non-positive"
result = if x > 0
"Positive"
else
"Non-positive"
end
七、布尔函数 #
7.1 类型检查 #
julia
isa(1, Int)
isa(1.0, Int)
typeof(1) == Int
7.2 集合检查 #
julia
in(1, [1, 2, 3])
1 ∈ [1, 2, 3]
1 ∉ [1, 2, 3]
7.3 范围检查 #
julia
in(5, 1:10)
5 in 1:10
7.4 字符串检查 #
julia
occursin("Julia", "Hello Julia")
startswith("Hello Julia", "Hello")
endswith("Hello Julia", "Julia")
contains("Hello Julia", "Julia")
八、实践练习 #
8.1 练习1:条件判断 #
julia
function classify_number(n)
n > 0 ? "Positive" : n < 0 ? "Negative" : "Zero"
end
classify_number(5)
classify_number(-3)
classify_number(0)
8.2 练习2:短路求值 #
julia
function safe_sqrt(x)
x >= 0 && return sqrt(x)
return nothing
end
safe_sqrt(4)
safe_sqrt(-1)
8.3 练习3:布尔逻辑 #
julia
function is_valid_age(age)
age >= 0 && age <= 120
end
function can_vote(age, citizenship)
age >= 18 && citizenship == "citizen"
end
is_valid_age(25)
can_vote(20, "citizen")
8.4 练习4:条件执行 #
julia
function process(x)
x < 0 && return "Negative"
x == 0 && return "Zero"
x > 100 && return "Large"
return "Small positive"
end
process(-5)
process(0)
process(50)
process(150)
九、总结 #
本章我们学习了:
- 布尔值:true和false
- 比较运算:相等、大小、链式比较
- 逻辑运算:与、或、非
- 短路求值:&&和||的短路特性
- 三元运算符:条件表达式
- 布尔函数:类型检查、集合检查
接下来让我们学习Julia的Nothing类型!
最后更新:2026-03-27