Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Macro to add coalesce(x, false) to all if and && and || in a block #133

Open
pdeffebach opened this issue May 12, 2021 · 3 comments
Open

Comments

@pdeffebach
Copy link
Contributor

Should this live in Missings.jl? Potentially cleaner and easier to maintain than a skipmissing keyword argument in more functions.

Note that it uses postwalk so @mfalse can act recursively on nested expressions.

julia> using MacroTools

julia> function mfalse_helper(ex::Expr)
           MacroTools.postwalk(ex) do x
               if x isa Expr && x.head == :if 
                   x.args[1] = wrap_coalesce(x.args[1])
               elseif x isa Expr && x.head == :&&
                   x.args = wrap_coalesce.(x.args)
               elseif x isa Expr && x.head == :|| 
                   x.args = wrap_coalesce.(x.args)
               end
               x
           end  
       end;

julia> wrap_coalesce(x::Expr) = :(coalesce($x, false));

julia> wrap_coalesce(x::Symbol) = :(coalesce($x, false));

julia> wrap_coalesce(x) = x;

julia> macro mfalse(x)
           esc(mfalse_helper(x))
       end;

julia> x = missing;

julia> x == 1 ? 2 : 3
ERROR: TypeError: non-boolean (Missing) used in boolean context
Stacktrace:
 [1] top-level scope
   @ REPL[21]:1

julia> @mfalse x == 1 ? 2 : 3
3

Now that .|| and .&& are in Base, we can also account for these in the macro.

@pdeffebach
Copy link
Contributor Author

pdeffebach commented May 12, 2021

This was inspired by JuliaLang/julia#40729, which introduces a @coalesce macro. So maybe this can be added to Base?

It's also reminiscent of some of the three-valued logic in Volcanito.jl.

@nalimilan
Copy link
Member

Interesting. Do you plan to use this in DataFramesMeta? I think it would be useful to consider practical use cases first.

@pdeffebach
Copy link
Contributor Author

Yes, I'm thinking of something like

@subset df @byrow :x == 1 || :x == 2

which would fail if :x is missing, even if we did subset(...; skipmissing = true).

@subset df @byrow @mfalse :x == 1 || :x == 2

would work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants