Elixir

Elixir Basics - 1. Basic Data Types

Updated:

Integers

Elixir supports a variety of different Integers.

Decimal

iex(1)> 14
14
iex(19)> i(14)
Term
  14
Data type
  Integer
Reference modules
  Integer
Implemented protocols
  IEx.Info, Inspect, List.Chars, String.Chars

Underscores can also be used with Decimal numbers when writing large numbers, making them easier to read.

For example, one million can be written like so

iex(5)> 1_000_000
1000000

Hexadecimal

iex(2)> 0xcafe
51966

Octal

iex(3)> 0o765
501

Binary

iex(4)> 0b1010
10

Floats

A Float or Floating-point number is denoted by using a decimal point.

iex(6)> 5.0
5.0
Term
  5.0
Data type
  Float
Reference modules
  Float
Implemented protocols
  IEx.Info, Inspect, List.Chars, String.Chars

Floats also support exponents by using the letter e after the last number.

iex(16)> 3.14e-2
0.0314

Booleans

Elixir supports both true and false as booleans

iex(17)> true
true
iex(18)> false
false
iex(19)>
Term
  true
Data type
  Atom
Reference modules
  Atom
Implemented protocols
  IEx.Info, Inspect, List.Chars, String.Chars

If you are paying attention, you will notice that when you inspect i(true) Elixir says that its data type is of type Atom. This is because booleans in Elixir are also atoms

iex(25)> is_atom(true)
true
iex(26)> is_atom(false)
true

Atoms

An Atom is a constant whose name is its value.

iex(27)> :foo
:foo
iex(37)> i(:foo)
Term
  :foo
Data type
  Atom
Reference modules
  Atom
Implemented protocols
  IEx.Info, Inspect, List.Chars, String.Chars
iex(33)> is_boolean(:true)
true
iex(34)> is_boolean(:false)
true
iex(35)> :true === true
true
iex(36)> :false === false
true

Strings

Strings are denoted with double quotes.

iex(38)> "Hello, World"
"Hello, World"
iex(39)> i("Hello, World")
Term
  "Hello, World"
Data type
  BitString
Byte size
  12
Description
  This is a string: a UTF-8 encoded binary. It's printed surrounded by
  "double quotes" because all UTF-8 encoded code points in it are printable.
Raw representation
  <<72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100>>
Reference modules
  String, :binary
Implemented protocols
  Collectable, IEx.Info, Inspect, List.Chars, String.Chars

Elixir also supports string interpolation, like so:

iex(41)> string = "World"
"World"
iex(42)> "Hello, #{string}"
"Hello, World"

Strings can be printed using IO.puts() from the IO module.

iex(43)> IO.puts("Hello, World")
Hello, World
:ok

Sources

Previous
11. Functions