# How can I determine the type of a packed array?

Packed arrays can be of type Integer, Real or Complex. Knowing that an array arr is packed, how can I efficiently determine its type?

We can use one of several ways. First, let us create some test data:

arr = Range[10]; (* this is an Integer packed array *)
unpacked = {1, 2, 3} (* this is an Integer array that is NOT packed *)


Since Mathematica 10.4, InternalPackedArrayType directly returns the type:

InternalPackedArrayType[arr]
(* Integer *)

InternalPackedArrayType[unpacked]
(* $Failed *)  DeveloperPackedArrayQ has a second argument, which is the type of the array. This way we can test both for the type and "packedness" at the same time. DeveloperPackedArrayQ[arr, Integer] (* True *) DeveloperPackedArrayQ[arr, Real] (* False *) DeveloperPackedArrayQ[unpacked, Integer] (* False *)  This function is useful in specializing functions for processing packed array of various types, e.g. to dispatch to the appropriate LibraryLink function. A third argument allows testing for the array depth as well. To get the type directly in versions of Mathematica prior to 10.4, without testing for each possible type using PackedArrayQ, we can extract an element and check its head: packedArrayType[arr_?DeveloperPackedArrayQ] := Head@Extract[arr, Table[1, {ArrayDepth[arr]}]] packedArrayType[___] :=$Failed


This is roughly what NDSolveFEMPackedArrayType does, which confirms to me that this is the appropriate way. In a package, I would define packedArrayType in a version-dependent manner as

If[\$VersionNumber >= 10.4,
packedArrayType = InternalPackedArrayType,
packedArrayType[...] := (* manual method from above *)
]


There's another useful function for this kind of thing

arr = RandomReal[1, 10^8];
DeveloperPackedArrayForm[arr]

"PackedArray"[Real, "<" 100000000 ">"]


The drawback is that this is for display purposes only, it doesn't seem to be possible to extract the Real from this.

on second thoughts, this seems to work:

DeveloperPackedArrayForm[Range[10]] // ToBoxes // MakeExpression // #[[1, 1]] &

Integer

• That's why I expected that there has to be a way to determine the type. Only when I saw NDSolveFEMPackedArrayType` was I finally convinced that there is not (for M < 10.4). – Szabolcs Oct 10 '17 at 9:00
• @Szabolcs hacky approach, but see update. – LLlAMnYP Oct 10 '17 at 9:04