17
$\begingroup$

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.

$\endgroup$
0

2 Answers 2

26
$\begingroup$

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}
$\endgroup$
4
$\begingroup$

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).

$\endgroup$
4
  • 3
    $\begingroup$ 1) But why do you think so? Sequence does not care about being in a List or not: h[a, Sequence[]]. 2) you don't need Unevaluated because Rule is SequenceHold. $\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 with Sequence[] (that is also backward compatible). Is there perhaps an example, where one can achieve something really useful with Nothing that you can't get with Sequence? As for 2), you are of course right, Rule is a wrong example here. But Map and If do not have the HoldSequence attribute, so there Unevaluated is actually needed (AFAIK): Map[If[# === a, Sequence[],#]&,{a,b,c,d}] vs. Map[If[# === a, Unevaluated[Sequence[]],#]&,{a,b,c,d}]. $\endgroup$
    – vsht
    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) Nothing is not really needed to achieve the same effect. I probably should have stated it as a comment, not an answer. $\endgroup$
    – vsht
    May 30, 2018 at 8:46
  • $\begingroup$ Ad ad 1) It is shorter to write If[cond, sth, Nothing] than Unevaluated @ 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 where Nothing left in other heads would be very useful but maybe someone did. $\endgroup$
    – Kuba
    May 30, 2018 at 8:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.