type_of(): Variable Type Detection in Erlang
July 24, 2008 8:01 pm Erlang, Programming, Tools and Libraries[digg-reddit-me]Amusingly, there isn’t actually a way to ask Erlang the type of a variable, and new programmers often struggle with this on basis of not realizing they’re expected to use is_foo() guards.
This function, type_of(), resolves the issue. As such, none of the testing stuff is included; that’s all in the library, rather than here on the blog.
If you’re running Erlang 11 or earlier, the bitstring clause will fail. That is a new type. Just comment it out and move on with your day; it’s a synonym for “binary” and on your system the word “binary” will come out instead.
type_of(X) when is_integer(X) -> integer;
type_of(X) when is_float(X) -> float;
type_of(X) when is_list(X) -> list;
type_of(X) when is_tuple(X) -> tuple;
type_of(X) when is_bitstring(X) -> bitstring; % will fail before e12
type_of(X) when is_binary(X) -> binary;
type_of(X) when is_boolean(X) -> boolean;
type_of(X) when is_function(X) -> function;
type_of(X) when is_pid(X) -> pid;
type_of(X) when is_port(X) -> port;
type_of(X) when is_reference(X) -> reference;
type_of(X) when is_atom(X) -> atom;
type_of(_X) -> unknown.

July 25th, 2008 at 5:32 am
Hi,
is_binary is not redundant in R12
4> BS = <>.
<>
5> is_binary(BS).
false
6> is_bitstring(BS).
true
The question is if for a binary (as in the old kind) you want to return ‘binary’ or ‘bitstring’. I think ‘binary’ is correct, in which case that clause should be put before the bitstring one.
regards,
Vlad
July 25th, 2008 at 9:45 am
That’s interesting, Vlad. I’m glad you told me about the redundancy issue. I’ve removed that comment.
Before I re-order binary in front of bitstring, I’d like to know why you believe returning binary is preferable; I was under the (possibly incorrect) belief that the title “binary” was deprecated.
July 25th, 2008 at 10:29 am
Binary is not deprecated. It is a subset of bitstrings. In fact it is the subset of bitstrings whose size in bits is evenly divisible by eight. This means that withyour current ordering the function will never return binay since all binaries are also bitstrings.
July 25th, 2008 at 4:13 pm
“…not realizing they’re expected to use is_foo() guards. This function, type_of(), resolves the issue.”
I’m not sure how type_of() resolves the issue of new programmers not realizing they should use guards.
But the implementation does server as a good example of using guards. Is that your point?
July 25th, 2008 at 6:12 pm
No, the point is that having to write out more than a dozen guards each time you want to discover something’s type is silly and a hassle.
July 25th, 2008 at 6:15 pm
Mr. Gustafsson: it becomes clear that I need to read more about bitstrings. Thank you for the clarification; expect a fix by monday. (I believe this is also what Vlad was trying to tell me.)