1
$\begingroup$

Consider this example:

lis1 = {a, b, c};
lis1[[2]] = Sequence[e, f];
lis1
(*{a, e, f, c}*)
lis1[[2]]
(*e*)
lis1[[2]] = Sequence[g, h];
lis1
(*{a, g, h, c}*)

It looks like position 2 in lis1 is still has head Sequence, yet no sign of Sequence in the full form of lis1.

Can any one explain why is this happening?

$\endgroup$
4
  • 5
    $\begingroup$ Have a look at this. $\endgroup$ Commented Sep 11, 2014 at 21:33
  • $\begingroup$ @LeonidShifrin, lis1 = DeleteCases[lis1, Sequence, -1]; will completely solve the problem but I get confused how to explain this because Sequence is a head and as far as I know you can not completely delete head but replace head by another head. $\endgroup$ Commented Sep 11, 2014 at 21:58
  • 1
    $\begingroup$ Read more carefully the linked explanation. In DeleteCases, Sequence disappears in lis1 as a result of evaluation. $\endgroup$ Commented Sep 11, 2014 at 22:05
  • $\begingroup$ @LeonidShifrin thanks a lot. I got it now. $\endgroup$ Commented Sep 11, 2014 at 23:00

1 Answer 1

1
$\begingroup$

I think this readily explained by looking at the own-values of the variable after the assignment is made.

v = {a, b, c}; v[[2]] = Sequence[e, f];
OwnValues @ v
{HoldPattern[v] :> {a, Sequence[e, f], c}}

It's rather like Defer, so it will behave like {a, e, f, c} under standard evaluation. But it can behave differently in non-standard evaluation. When this would be a problem, you can always do

v = v
{HoldPattern[v] :> {a, e, f, c}}

to get variable bound to the fully evaluated form.

$\endgroup$
3
  • $\begingroup$ Set using non-standard evaluation wouldn't alone be enough to provide this behavior. The key here is that Set and SetDelayed (as well as Rule and RuleDelayed) are also SequenceHold. $\endgroup$ Commented Sep 11, 2014 at 22:08
  • $\begingroup$ @LeonidShifrin. You're right. I did not mean to imply the Set alone was the culprit. Bad wording on my part. I will try to fix it. $\endgroup$
    – m_goldberg
    Commented Sep 11, 2014 at 22:11
  • $\begingroup$ No worries, I didn't mean that comment as a critique, just as an additional piece of information. $\endgroup$ Commented Sep 11, 2014 at 22:16

Your Answer

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

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