Maybe this is a boring question, but I cannot figure it out. Because every expression has a Head
, and Head[1]
is Integer
, and Head[Integer]
is Symbol
. Therefore, 1
should somehow represented as Symbol["Integer"][1]
or something similar. However, Depth[1]
is one which means 1
should be presented as Symbol["Integer..."]
, not as a expression of depth 2, such as Symbol["Integer"][1]
.
What is correct representation of 1
?
Answer
In Mathematica there are compound expressions and atomic expressions.
Anything that AtomQ
returns True
for is atomic, and may behave in "strange" ways. These must be considered indivisible by users, and only standard and documented ways should be used to extract information from them.
All the rest are compound expressions and have the form head[arg1, arg2, ...]
. Here head
is the head of the compound expression.
Atomic expressions have "heads" too, by convention. These do not indicate a structure. They are used in practice to indicate the type of the atomic expression so we can programatically distinguish an Integer
from a Real
. The fact that Head[1]
returns Integer
does not imply that 1
is somehow represented as Integer[...]
because AtomQ[1]
is True
.
Finally a warning:
Don't be fooled by what e.g. FullForm
might show for an atomic expressions (e.g. FullForm[2/3]
is Rational[2,3]
which looks like it has a structure: an explicit head and two arguments. In reality it doesn't. AtomQ[2/3]
is True
. In practice atomic objects vary in how they behave when you attempt to disassemble them, but none of them work with all functions that would allow looking into their structure (such as pattern matching on the structure FullForm
shows, Part
, Extract
, Depth
, etc.). When you work with some objects, you must read their documentation and only handle them in standard and documented ways. Otherwise your code might misbehave in ways you didn't expect.
Other than the most basic data types in Mathematica (Symbol
, String
, Integer
, Rational
, etc.) there are more complex atomic objects such as SparseArray
, Graph
, Image
, MeshRegion
, etc. These are made to be atomic so that they can have a more efficient internal implementation.
Comments
Post a Comment