If someone is feeling especially impish, they don’t even need to wait for this to change in the base language.
using IRTools
istruthy(b::Bool) = b
istruthy(x) = convert(Bool, x)
istruthy(s::String) = s != ""
istruthy(t::Tuple) = length(t) != 1
IRTools.@dynamo function truthy(f, args...)
ir = IRTools.IR(f, args...)
ir === nothing && return
IRTools.recurse!(ir)
for block in IRTools.blocks(ir)
bblock = IRTools.BasicBlock(block)
for b in eachindex(IRTools.branches(bblock))
branch = bblock.branches[b]
if IRTools.isconditional(branch)
converted = push!(block, IRTools.xcall(@__MODULE__(), :istruthy, branch.condition))
bblock.branches[b] = IRTools.Branch(branch; condition=converted)
end
end
end
return ir
end
julia> truthy() do
if (1,)
println("hi")
end
end
hi
julia> function bar(s::String)
while s
s = s[1:end-1]
@show s
end
s
end
bar (generic function with 2 methods)
julia> truthy() do
bar("Hello")
end
s = "Hell"
s = "Hel"
s = "He"
s = "H"
s = ""
""
Credit (or blame) for this monstrosity to Phipsgabler (not sure what his discourse handle is) sloppyif.jl · GitHub
All these fancy-schmancy notions of “correctness”, “consistency” and “error resistance” in Julia feel so 20th century to me. Those other languages have apparently embraced postmodern relativism, that truth can be whatever feels right to you depending on your viewpoint and daily mood. That approach is clearly more inline with the Zeitgeist, as evidenced in the news every day. It’s sad to see Julia so out of touch with our times.
if p = function_with_optional_result(...)
# use p, as it is non-null
end
is a common pattern in, for example, the LLVM code base.
I’m not saying this is a better convention than explicit optional types (or returning nothing that’ll throw an error if you try to use it as a pointer), but it’s still fairly convenient.
Ptr types may not be integers, but it’s fairly reasonable to have them behave the same way, and thus have truthiness of integers also be based on comparison to zero.
I don’t know the history, but this also fits the pattern of C vs Lisp having settled on different conventions of truthiness for integers.
I will say that adding booleans is something I’ve done quite a few times before, basically counting the number of times something happened etc. I guess one could cast the bools to int to do that but it’s a bit verbose.
that’s just Vacuous truth - Wikipedia which is very common. The problem with Python is [] can be interpreted as Boolean, which Julia is very much not able to