Print the type, not string rep of a value?

To print the string rep of a variable, we can do:


Now, however, suppose all I want is to get the type of the value, not the string rep. How do I do that ?

There’s no built-in function to do that. IEx has a helper i that you can use in the shell. If you’re not on the shell, you can also use it via, but it will also return other information and not just type.

Stack Overflow has examples on how to do it manually:

defmodule Util do
    def typeof(self) do
        cond do
            is_integer(self)    -> "integer"
            is_float(self)      -> "float"
            is_atom(self)       -> "atom"
            is_boolean(self)    -> "boolean"
            String.valid?(self) -> "string"    # Not a real type
            is_binary(self)     -> "binary"
            is_bitstring(self)  -> "bitstring"
            is_function(self)   -> "function"
            is_list(self)       -> "list"
            is_tuple(self)      -> "tuple"
            is_pid(self)        -> "pid"
            is_port(self)       -> "port"
            is_reference(self)  -> "reference"
            is_exception(self)  -> "exception" # Not a real type
            is_struct(self)     -> "struct"    # Not a real type
            is_map(self)        -> "map"
            true                -> "idunno"

Thanks! I did not realize, until now, that Elixir, lacking generics, only has a finite # of types (counting all structs as one type or now). This makes a lot of sense now.

Seems like such a handy thing, that I have to wonder if it was omitted deliberately. Maybe the core team didn’t want to encourage looking at such details, for language-design reasons?

With pattern matching, there should never be a need to do this for anything other than debugging (though I’ve never found myself wanting this in debugging either). Do you have any examples of where you want to use it?