I just considered if/how one could implement Sequence
in Mathematica if it were not predefined. It turned out that the following simple definition has in all my tests exactly the right behaviour:
myseq /: f_[x___, myseq[y___], z___] := f[x, y, z]
Now my question: Does this already correctly reproduce the full behaviour of Sequence
, or is there something Sequence
does but myseq
doesn't which I missed in my tests?
Here's what I tested:
foo[myseq[a, b]]
(*
==> foo[a, b]
*)
Hold[mysec[a,b]]
(*
==> Hold[a, b]
*)
HoldComplete[myseq[a,b]]
(*
HoldComplete[myseq[a, b]]
*)
Hold[f[myseq[a,b]]]
(*
==> Hold[f[myseq[a, b]]]
*)
f[myseq[myseq[a,b],c,d],e,myseq[f,g,myseq[]]]
(*
==> f[a, b, c, d, e, f, g]
*)
Answer
Ok, my two cents. The answer seems to be - you can't. There are 3 "magic" symbols which are wired into the core evaluator much deeper than the rest: Evaluate
, Unevaluated
, and Sequence
. You can't fully emulate any of those without essentially writing your own version of Mathematica evaluator on top of the built-in one.
For the record, I first read about it in the book of David Wagner, "Power programming with Mathematica - the Kernel", p.207. Which means - if this is correct, I take the credit, but if it is wrong, he is the one to blame :). But, seriously, there was nothing in my experience to contradict this. You may emulate some aspects of Sequence
, but I would be very surprised if you could make a complete emulation (without writing your own evaluator on top of the system one).
Let me also add that, while it is hidden, you do use Sequence
in your approach, since the y___
pattern is internally destructured as Sequence
. Check this out:
ClearAll[myseq];
myseq /: f_[x___, myseq[y___], z___] := f[x, Head[Unevaluated[y]], z]
and now
f[1, myseq[], 5]
f[1, Sequence, 5]
Comments
Post a Comment