You could make a symbol that turned any Rule
it is part of into Nothing
with something like
In[28]:= ClearAll[associationNothing]
associationNothing /: Rule[key_, associationNothing] := Nothing
In[30]:= <|"a" -> 1, "b" -> associationNothing, "c" -> 3|>
Out[30]= <|"a" -> 1, "c" -> 3|>
but this means the substitution happens anywhere, not just in an association:
In[31]:= b -> associationNothing
Out[31]= Nothing
In[32]:= {c -> associationNothing, d, 3}
Out[32]= {d, 3}
If this isn't something you want to happen you could do some shenanigans with the stack to get around the rules for up values:
ClearAll[associationNothing]
associationNothing /: Rule[key_, associationNothing] := Nothing /; MatchQ[
Stack[],
{___, Association, List, associationNothing, RuleCondition, MatchQ}
]
which should meet the requirements:
In[38]:= {c -> associationNothing, <|d -> associationNothing|>, 3}
Out[38]= {c -> associationNothing, <||>, 3}
I think it's crazy, but it just might work.
narrator: it does not work
The above shenanigans only work when constructing an association directly, it does not work when modifying an existing association:
In[49]:= assoc = <|"a" -> 1, "b" -> associationNothing, "c" -> 1|>
Out[49]= <|"a" -> 1, "c" -> 1|>
In[50]:= assoc["d"] = associationNothing
Out[50]= associationNothing
In[51]:= assoc
Out[51]= <|"a" -> 1, "c" -> 1, "d" -> associationNothing|>
I don't know a way around this.
DeleteCases[#, Nothing] &
to the association $\endgroup$Values[<|a -> 1, b -> Nothing|>]
giving{1}
. And we have<|a -> 1, Nothing|>
resolving to<|a -> 1|>
. And we haveDeleteCases[<|"a" -> 1, "b" -> Nothing|>, Nothing]
giving<|"a" -> 1|>
. So, in what way are these unsatisfactory for the use cases you envision? $\endgroup$<|a -> 1, b -> 2|> // KeyDrop[b]
? $\endgroup$Map[f, <| a->1, b->Nothing |>]
gives<|a->f[1], b->f[Nothing]|>
, for example. $\endgroup$Missing[]
as somewhat the role ofNothing
for associations in the sense that the heads of the results of<|a -> 1, b -> Missing[]|>[b]
and<|a -> 1|>[b]
will be the same. AndDeleteMissing[<|a -> 1, b -> Missing[]|>[b]]
returns<|a -> 1|>[b]
. It does not work as desired by OP forMap
, though. $\endgroup$