没有 else 的 Julia 三元运算符

Julia ternary operator without `else`

考虑 Julia 中的三元运算符

julia> x = 1 ; y = 2

julia> println(x < y ? "less than" : "not less than")
less than

问题:有没有办法省略语句中的:部分?相当于

的东西
if condition
    # dosomething
end

没有写如果条件不满足就什么都不做

注意:我研究了答案但没有结果,即使在相关问题中也是如此(, )

就这样:

condition && do_something

举个例子:

2 < 3 && println("hello!")

解释:

&& 是 Julia 中的短路运算符。因此,第二个值仅在需要评估时才评估。因此,当第一个 condition 评估为 false 时,无需评估第二部分。

最后,请注意,您也可以在作业中使用它:

julia> x = 2 > 3 && 7
false

julia> x = 2 < 3 && 7
7

然而,这会使 x 类型不稳定,因此您可能希望将赋值的右侧包裹在 Int 周围,例如 x = Int(2 > 3 && 7) 而不是 x 将始终如此一个 Int.

&& 通常用于此,因为它很短,但您必须知道阅读它的技巧。有时我发现只使用常规的旧 if 语句更具可读性。在 Julia 中,如果你想保存 space.

,它不需要跨越多行
julia> x = 1; y = 2;

julia> if (x < y) println("less than") end
less than

julia> if (x > y) println("greater than") else println("not greater than") end
not greater than

请注意,在这种情况下,条件句周围不需要括号;为了清楚起见,我只是添加它们。另外,请注意,为了清楚起见,我将 println 移到了字符串旁边,但如果您愿意,您可以将整个 if 语句放在 println 中,就像您在问题中所做的那样。