How do you check for the type of variable in Elixir

Low Kian Seong picture Low Kian Seong · Feb 7, 2015 · Viewed 67.2k times · Source

In Elixir how do you check for type such as in Python:

>>> a = "test"
>>> type(a)
<type 'str'>
>>> b =10
>>> type(b)
<type 'int'>

I read in Elixir there are type checkers such as 'is_bitstring', 'is_float', 'is_list', 'is_map' etc, but what if you have no idea what the type could be ?

Answer

Fred the Magic Wonder Dog picture Fred the Magic Wonder Dog · Feb 24, 2016

Starting in elixir 1.2 there is an i command in iex that will list the type and more of any Elixir variable.

iex> foo = "a string" 
iex> i foo 
Term
 "a string"
Data type
 BitString
Byte size
 8
Description
 This is a string: a UTF-8 encoded binary. It's printed surrounded by
 "double quotes" because all UTF-8 encoded codepoints in it are        printable.
Raw representation
  <<97, 32, 115, 116, 114, 105, 110, 103>>
Reference modules
  String, :binary

If you look in the code for the i command you'll see that this is implemented via a Protocol.

https://github.com/elixir-lang/elixir/blob/master/lib/iex/lib/iex/info.ex

If you want to implement a function for any Data type in Elixir, the way to do that is to define a Protocol and implementation of the Protocol for all the data types you want the function to work on. Unfortunately, you can't use a Protocol function in guards. However, a simple "type" protocol would be very straightforward to implement.