How was Nothing
implemented in Wolfram language at the language level?
For example, {a, b, Nothing, c, d, Nothing}
will return {a, b, c, d}
. How does Nothing
here affect the List
? I can't see what mechanism can achieve this effect.
2 Answers
Ok, I failed to find a duplicate so here is my comment:
I don't know how Nothing
is internally implemented but you can do something like this with UpValues
:
nothing /: {a___, nothing, b___} := {a, b}
I would speculate that the internal implementation might build upon Sequence[]
. Consider
{a, b, Sequence[], c, d, Sequence[]}
which evaluates to
{a, b, c, d}
However, to use that in replacement rules, you need to wrap it in Unevaluated
like this
{a, b, c, d} /. c -> Unevaluated[Sequence[]]
which gives
{a,b,d}
P.S. I found out about Sequence[]
from some answer on this site some years ago, but I don't remember which one exactly. I use it since then in all my codes, so that I consider Nothing
just some sort of syntactic sugar (which is also not compatible with older Mathematica versions).
-
3$\begingroup$ 1) But why do you think so?
Sequence
does not care about being in aList
or not:h[a, Sequence[]]
. 2) you don't needUnevaluated
becauseRule
isSequenceHold
. $\endgroup$– Kuba ♦May 30, 2018 at 6:45 -
$\begingroup$ Regarding 1) I just fail to see much sense for using
Nothing
where one can usually get the same effect withSequence[]
(that is also backward compatible). Is there perhaps an example, where one can achieve something really useful withNothing
that you can't get withSequence
? As for 2), you are of course right,Rule
is a wrong example here. ButMap
andIf
do not have theHoldSequence
attribute, so thereUnevaluated
is actually needed (AFAIK):Map[If[# === a, Sequence[],#]&,{a,b,c,d}]
vs.Map[If[# === a, Unevaluated[Sequence[]],#]&,{a,b,c,d}]
. $\endgroup$– vshtMay 30, 2018 at 8:24 -
$\begingroup$ Well, I guess my answer is anyhow offtopic, since the original question was really about the implementation. I just wanted to point out that (IMHO)
Nothing
is not really needed to achieve the same effect. I probably should have stated it as a comment, not an answer. $\endgroup$– vshtMay 30, 2018 at 8:46 -
$\begingroup$ Ad ad 1) It is shorter to write
If[cond, sth, Nothing]
thanUnevaluated @ Sequence[]
, and more readable than##&[]
so it is not like a long awaited solution but rather a small feature to make code cleaner. I didn't face a use case whereNothing
left in other heads would be very useful but maybe someone did. $\endgroup$– Kuba ♦May 30, 2018 at 8:48