12

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?

Kagaratsch
  • 11,955
  • 4
  • 25
  • 72
  • 7
    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 08 '14 at 15:51
  • 2
    Depending on what you are doing, you may also be interested in Blank with a Head specified, like _Integer, _String, _a – mfvonh Oct 08 '14 at 15:54
  • 1
  • @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 08 '14 at 18:20

1 Answers1

13

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,
      Head /@ 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]]

enter image description here

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]

enter image description here

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

eldo
  • 67,911
  • 5
  • 60
  • 168