5
$\begingroup$

Why does Head[Sequence[b, c]] return c[Symbol] and not Sequence?

Why does Head[[b, c]] return an error: The expression b cannot be used as a part specification

I am trying to determine the behaviour of Sequence in Mathematica. It seems an unusual expression.

$\endgroup$
3
  • 3
    $\begingroup$ Because a rule causes it to evaluate to Head[b, c]: Examine Trace[Head[Sequence[b, c]]]. (2) Head[[b, c]] is short-hand for Part[Head, b, c]: examine FullForm[Head[[b, c]]]. $\endgroup$ Commented May 18, 2020 at 21:34
  • 1
    $\begingroup$ Maeder writes about this in Programming with Mathematica. Sequence[] often behaves differently when used with other functions due to its special properties, so one needs to do things differently if you're doing things with it. $\endgroup$ Commented May 19, 2020 at 2:39
  • $\begingroup$ Thanks @MichaelE2 That makes sense, this is the splicing rule I read about. Thanks JM I will look up the reference. $\endgroup$ Commented May 19, 2020 at 8:51

1 Answer 1

7
$\begingroup$

Head[Sequence[b, c]] returns an error (Head::argx: Head called with 2 arguments; 1 argument is expected) on my system (MMA 12.0, Win10-64). This makes sense because Head has no Hold attributes, so Sequence is evaluated within Head, leading to Head being called with two arguments, i.e. Head[b, c]. Look at the Trace output:

Trace @ Head[Sequence[b, c]] {HoldForm[Head[Sequence[b, c]]], HoldForm[Head[b, c]], {HoldForm[Message[Head::argx, HoldForm[Head], HoldForm[2]]], .... } 

You can write your own function that holds sequences:

ClearAll[myHead] myHead[expr_] := Head@Unevaluated@expr SetAttributes[myHead, SequenceHold] myHead[Sequence[b, c]] (* Out: Sequence *) 

As to the second part of your question, Head[[b, c]] is interpreted as an application of Part (i.e. [[...]]), so MMA thinks that you are trying to take part (b,c) of object Head.

$\endgroup$
1
  • $\begingroup$ Thanks that makes it very clear. $\endgroup$ Commented May 19, 2020 at 9:50

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.