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?
Sequencedoes not care about being in aListor not:h[a, Sequence[]]. 2) you don't needUnevaluatedbecauseRuleisSequenceHold. $\endgroup$Kuba– Kuba2018-05-30 06:45:42 +00:00Commented May 30, 2018 at 6:45 - $\begingroup$ Regarding 1) I just fail to see much sense for using
Nothingwhere 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 withNothingthat you can't get withSequence? As for 2), you are of course right,Ruleis a wrong example here. ButMapandIfdo not have theHoldSequenceattribute, so thereUnevaluatedis actually needed (AFAIK):Map[If[# === a, Sequence[],#]&,{a,b,c,d}]vs.Map[If[# === a, Unevaluated[Sequence[]],#]&,{a,b,c,d}]. $\endgroup$vsht– vsht2018-05-30 08:24:19 +00:00Commented May 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)
Nothingis not really needed to achieve the same effect. I probably should have stated it as a comment, not an answer. $\endgroup$vsht– vsht2018-05-30 08:46:15 +00:00Commented May 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 whereNothingleft in other heads would be very useful but maybe someone did. $\endgroup$Kuba– Kuba2018-05-30 08:48:25 +00:00Commented May 30, 2018 at 8:48