Data Structures in Elixir

Published September 25, 2018 by Toran Billups

In part 2 of my Elixir journey I'll be highlighting the various data structures and some of their performance characteristics.

Data Structures

Tuples are ordered collections of values. Unlike lists in Elixir tuples are stored uninterrupted, or contiguously in memory. This means that getting the size of the data structure or accessing an element in the tuple by index is fast. The tradeoff is that updating or adding elements to a tuple is costly because it requires creating a new tuple in memory.

    { 1, 2 }
    { :ok, 5, "foo" }

Tuples usually have 2-4 elements. If you need more you should look at using a map instead. Tuples are commonly seen in Elixir as return values from functions and this unlocks a great deal of pattern matching.

Lists are linked data structures. They are easy to traverse linearly but they are expensive to access in random order.

    a = [1, 2, 3]

You can combine 2 lists using the ++ operator. Returns [1, 2, 3, 4, 5]

    [1, 2, 3] ++ [4, 5]

You can diff 2 lists using the -- operator. Returns [1, 3]

    [1, 2, 3] -- [2]

You can ask if a element is in a given list. Returns a boolean of true in this case

    1 in [1, 2, 3]

You can create a list of tuples made up of key/values using a shorthand.

    [ name: "Toran", city: "foo" ]

This will then be converted into ...

    [{ :name, "Toran" }, { :city, "foo" }]

Map is a collection of key/value pairs. Maps allow any value as a key. Maps' keys do not follow any ordering.

    states = %{ "IA" => "Iowa", "WI" => "Wisconsin" }

If the key is an atom you can use a shorthand.

    colors = %{ red: "red", green: "green" }

This will then be converted into ...

    %{ :red => "red", :green => "green" }

You can access any value of the map by using the key. Returns the value "Iowa"

    iowa = states["IA"]

You can use the built in Map functions to get with a given key

    Map.get(%{:a => 1, :b => 2}, :a)

You can use the built in Map functions to put a new key/value into the data structrue

    Map.put(%{:a => 1, :b => 2}, :c, 3)

Buy Me a Coffee

Twitter / Github / Email