12
$\begingroup$

I'm looking for a way to get the type of an object:

TypeOf["x"] -> String
TypeOf[1] -> Integer

Or something along those lines.

$\endgroup$
1
  • 4
    $\begingroup$ You need the function Head. $\endgroup$ May 7, 2016 at 20:27

2 Answers 2

16
$\begingroup$

Example:

list = {1, 2, 3};
integer = 1;
real = 0.1;

Head @ list
Head @ integer
Head @ real

Output:

List

Integer

Real

Reference

Head

$\endgroup$
9
$\begingroup$

(Post adapted after comments.)

Mathematica 10 introduced a new type system local to Dataset, that's used like this:

Needs["TypeSystem`"]
DeduceType[{1, Sqrt[2], "test", {1, Sqrt[2], 3}, {1, 2, 3}}]

Mathematica graphics

In this type system a type is not the same as Head[expr]. In this framework the head of an atomic value is instead retrieved by TypeAtoms:

Mathematica graphics

But yes, for what you want to do you still need Head.

$\endgroup$
7
  • 1
    $\begingroup$ DeduceType is still undocumented. What are actual use cases for this new type system? $\endgroup$ May 7, 2016 at 20:58
  • 3
    $\begingroup$ This new type system serves primarily Dataset. It is not on the same fundamental level as Mathematica's core "type system", of which Head is part. It has a status of specific type system used by one or several application modules internally, and has no meaning in a more general context of fundamental Mathematica language / building blocks. $\endgroup$ May 7, 2016 at 21:16
  • $\begingroup$ @AlexeyPopkov So far it seems that it is mostly useful for debugging problems with Dataset, WReach has invoked it in several of his answers to explain different unintuitive behaviors. $\endgroup$
    – C. E.
    May 7, 2016 at 21:18
  • $\begingroup$ @LeonidShifrin It is true, but within this framework they refer to Integer, Real etc. as type atoms, not as types. So whether it is intentional or not they have introduced a new terminology for these labels. Yes, this is nitpicking. I see this as an opportunity to mention TypeSystem to readers who may not know about it. $\endgroup$
    – C. E.
    May 7, 2016 at 21:25
  • 2
    $\begingroup$ Each module is free to define its own notion of types, for its own purposes. For example, Compile also has a type system, which is different from either the new TypeSystem or the core Mathematica type system. Both Compile's type system and the new TypeSystem are incomplete - there are types they can't describe (but core Mathematica can). I agree that it is good to mention these, but the question about types in Mathematica in general has a clear and unique answer, and that answer is - atoms and normal expressions, where heads of expressions one may interpret as non-atomic types. $\endgroup$ May 7, 2016 at 21:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.