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.
Asked
Active
Viewed 2,949 times
17
Michael E2
- 235,386
- 17
- 334
- 747
Eric
- 1,191
- 7
- 20
2 Answers
26
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}
Kuba
- 136,707
- 13
- 279
- 740
4
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).
vsht
- 3,517
- 13
- 23
Sequencedoes not care about being in aListor not:h[a, Sequence[]]. 2) you don't needUnevaluatedbecauseRuleisSequenceHold.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}]. – vsht May 30 '18 at 08:24Nothingis not really needed to achieve the same effect. I probably should have stated it as a comment, not an answer. – vsht May 30 '18 at 08:46If[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. – Kuba May 30 '18 at 08:48