Get expression type?

Is there a built in function that distinguishes between different kinds of variables? I mean something like:

VariableType[ 123 ]


Number

VariableType[ f[x] ]


Function

VariableType[ x ]


Variable

A={{a,b},{c,d}};
VariableType[ A ]


List

Etc.? Please let me know how this function is actually called. Or maybe one can implement it?

• What you want is Head, although it cannot distinguish functions, because they are usual symbols in Mathematica. Try Head[{a,b,c}] or Head[1] or Head[1.0] – halirutan Oct 8 '14 at 15:51
• Depending on what you are doing, you may also be interested in Blank with a Head specified, like _Integer, _String, _a – mfvonh Oct 8 '14 at 15:54
• See also: (22449), (59671) – Mr.Wizard Oct 8 '14 at 18:07
• @Mr.Wizard It's a duplicate of the first link you provided. On the other hand, to find this link, you already have to know Head - of which the OP apparently wasn't aware of. To close or not to close ... – eldo Oct 8 '14 at 18:20

A few examples

fun[x_] := x^2

sphere = Graphics3D[{Sphere[{0, 0, 0}, 0.01]}, Boxed -> False, ImageSize -> 30];

str =
{"1", "Pi", "{f}", "f", "f[x]", "f+f", "Inactivate[f+f,Plus]",
"Hold[1+2+3]", "{1,{2,{3}}}", "fun[2]", "fun[x]", "Cos[Exp[x]]",
"Red", "sphere", "DateObject[{2014,10}]"};

table =
With[{exp = ToExpression /@ str},
Prepend[
Transpose[{
str,
exp,
LeafCount /@ exp,
Map[TreeForm[#,
AspectRatio -> 1,
ImageSize -> 40,
PlotStyle -> PointSize[Medium],
VertexRenderingFunction -> Function[{p}, Point[p]]] &,
exp]}],
Style[#, Bold, 16] & /@ {"Input", "Output", "Head", "Leaves", "Graph"}]];

Framed[
Grid[table,
Alignment -> Left,
Dividers -> All,
Spacings -> {{2, 2, 2, 2, 2}, 2},
BaseStyle -> {FontFamily -> "Helvetica"},
Background -> {None, {{Hue[.6, .15, .9], GrayLevel[.9]}}},
FrameStyle -> Directive[Thick, White]],
FrameMargins -> 0.5,
FrameStyle -> GrayLevel[.7]]


Grid[
Partition[
Map[TreeForm[#,
AspectRatio -> 1,
ImageSize -> 200,
EdgeRenderingFunction -> ({Black, Arrow[#, 0.2]} &)] &,
{1, {f}, f + f,
fun[x], Red, DateObject[{2014, 10}],
Hold[1 + 2 + 3], {1, {2, {3}}}, sphere}],
3],
Background -> GrayLevel@0.95,
Dividers -> All]


See the documentation for Head and read the tutorials linked therein:

Just for fun

a[b] + c[d] /. head_[_] :> head


a + c

a[b] + c[d] /. head_[_, _] :> head


Plus

• Great answer, but very complex... any possibility to have a brief explanation of the results? is the sort answer the function Head[]? Thanks!! – Matifou Nov 25 '16 at 23:04