Let’s talk about types. Hardening our foundation.

Booleans

Probably the type that needs the least amount of explanation.

You have true and false. You can even use :true and :false. You’ll see what that is when we deal with atoms.

Elixir provides us with the is_boolean(x) predicate function.

iex> is_boolean(true)
true
iex> is_boolean(1)
true
iex> is_boolean(:true)
true

For a complete list of predicate functions, head on over to the official docs.

Unlike some languages that will do the conversion for you, in Elixir the following will fail:

iex> 1 == "1"
false
true == "true"
false

Strings

Strings are UTF-8 encoded binaries. They’re written with double quotes, "Hello World".

With this you can do things like:

iex> "\u00c6"
"Æ"
iex> IO.puts "\u00c6"
Æ
:ok

You can use the String module to manipulate your strings.

iex> String.upcase("hello")
"HELLO"
iex> String.trim("    abcdef ") 
"abcdef"
...

When we run i "hello" we get a lot more information:

Term
  "hello"
Data type
  BitString
Byte size
  5
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
  <<104, 101, 108, 108, 111>>
Reference modules
  String, :binary
Implemented protocols
  IEx.Info, Collectable, Inspect, List.Chars, String.Chars

As you can see, strings are represented internally as binaries, which is why we have acces to the :binary Erlang module — in conjunction with the String module.

In the future we’ll explore Elixir/Erlang modules more thoroughly.

Atoms

Atoms are probably the simplest type. Think of them as constants, but where their names are their values.

A perfect example can be seen above, namely:

iex> true == :true
true
iex> true === :true
true

The Atom module only gives us two functions:

  • to_charlist/1
  • to_string/1
iex> :foo
:foo
iex> Atom.to_string :foo
"foo"

That’s it for now. We’ll cover lists, tuples and maps in the next few posts.