Best way to make "present?" function in Julia?

Rails has this function called .present? that really helps with one-liners

// i.e. is something not nothing, nil, missing, zilch, nada

What is the best way to replicate this behavior in Julia?

edit: this is kind of what I’m working with now:

is_nothing(cur_object) = false
is_nothing(cur_object::Void) = true
is_nothing(cur_object::Number) = iszero(cur_object)

is_present(cur_object) = !is_nothing(cur_object)

nothing, missing, and numbers ==0 have different semantics in Julia (which is a good thing). What you are asking for deviates from standard semantics, so you have to make your own choices and code them accordingly. The function above is a good way of doing this.

That said (and I hesitate to say this without more context) doing something like this in Julia is code smell.

@djsegal I recommend not considering typed zeros as unpresent values. The existence of an additive identity (we call that zero for Integers and some other structures), lets someone develop cascading and interacting logic that becomes this computer.

This should confer an awareness of the nonpresent.

function ispresent(x::T) where {P, T<:Union{Missing, Nothing, P}}
    !(iismissing(x) || isnothing(x))
1 Like

I don’t see the need for types above, I think that

ispresent(x) = x ≢ nothing && x ≢ missing

should be equivalent.

Yes, I use type annotations that not required as documentation to remind myself what containers of xs types’ should be.

I don’t think this has any performance impact, I would be surprised if it did not compile to essentially the same code. I just like & friends visually, ismissing is fine.

I find your syntax easier to read, too.

Just replying to remind myself to come back and explore what this weird equality operator is :slight_smile:

Nothing weird about it, just Unicode aliases:

julia> ≡
=== (built-in function)

julia> ≢
!== (generic function with 1 method)

I meant “Weird” in the sense of “I’ve never seen it before,” not “this is abhorrent to the natural order” :laughing:. Thanks for explaining though so I don’t have to go digging once I get back to a computer :slight_smile:

1 Like