15

Sometimes you need to check for the type of an expression. You use Head[data] to get answers.

Some data:

data = {7, 1.4, Red, "hp", hps};
Head /@ data
(*{Integer, Real, RGBColor, String, Symbol}*)

Is there summary of what kind of answers Head[] can give?

Dr. belisarius
  • 115,881
  • 13
  • 203
  • 453

1 Answers1

24

Head can return any head. There is no predefined list.

expr = myArbitraryHead[1, 2, 3];

Head[expr]
myArbitraryHead

A head does not even need to be a Symbol:

expr2 = (2 Pi)[x, y, z];

Head[expr2]
2 π

Most heads are shown explicitly in the FullForm of the expression:

FullForm[{"a" + "b", 1/3}]

Head /@ {"a" + "b", 1/3}
List[Plus["a", "b"], Rational[1, 3]]

{Plus, Rational}

Some heads are implicit, such as in the atomic objects String, Integer, and Symbol:

FullForm[{"a", 1, Pi}]

Head /@ {"a", 1, Pi}
List["a", 1, Pi]

{String, Integer, Symbol}


As a side note the head of an expression is also returned when you ask for Part zero:

3[[0]]
Integer

Because Part returns sequences wrapped in the original head of the expression you get a strange result if extracting {0}:

3[[{0}]]
Integer[Integer]
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
  • 5
    +1 Also, for atomic data types (Integer, Rational, etc. and some more, e.g. Graphs) it returns the type rather than the head. Though it is more of a philosophical question what the differences is between type and head in Mathematica. – István Zachar Apr 01 '13 at 09:26
  • +1 Mr.Wizard introducing terminology is nice. – Jacob Akkerboom Apr 01 '13 at 13:36
  • 2
    I voted for your answer, but I disagree with the hidden head part. We should not use StandardForm (or, rather, you probably meant particular formatting which visually looks as if we had a division) for determination of heads and other structural components. Let's apply Occam's razor principle and not multiply entities unnecessarily. As to implicit heads, this is probably ok, but even here I am not sure - those are really the heads of certain atomic types, and there are just very few of those - basically they exist because the syntax allows for string and numeric literals. – Leonid Shifrin Apr 01 '13 at 15:50
  • @Leonid I think I understand your point about "hidden" heads, and I agree that was a poor choice (and will be edited). As for implicit heads how would you state it? – Mr.Wizard Apr 01 '13 at 21:17
  • I'd just say that atomic types represented as string or numeric literals also have heads (as any expression in Mathematica), but these heads are assigned to them internally and don't follow from their FullForm representation. This refers to Integer, Real, String and Symbol (not sure if I forgot some). Something like that. – Leonid Shifrin Apr 02 '13 at 07:08
  • @Leonid I edited this 10 hours ago with that intention; how does it read to you? – Mr.Wizard Apr 02 '13 at 07:40
  • Sorry, I only read the comment. I think it is pretty good now. – Leonid Shifrin Apr 02 '13 at 07:44