Powered by AppSignal & Oban Pro

Lists or tuples?

lists-or-tuples.livemd

Lists or tuples?

Due to their performance characteristics, lists are frequently used for storing dynamically growing, possibly large, collections.

Tuples, on the other hand, are most useful for grouping a small, fixed number of values, for example to return them from a function.

A common pattern is to use ‘tagged tuples’, which consist of an atom and a value, for example {:ok, "result"}.

String.split returns a list:

# 💡 Try adding another word to `"hello world"`
String.split("hello world", " ")

String.split_at returns a 2-element tuple:

String.split_at("hello world", 3)

Base.decode16 returns a tagged tuple:

# 💡 Try changing the input so it contains an invalid character, such as 'z'
Base.decode16("666F6F626172")

In Elixir, it’s a convention to define two versions of functions that can fail:

  • One that returns a tagged tuple (:ok or :error) - useful when you want to handle errors gracefully
  • Another with a trailing ! that raises an error - useful when failures are unexpected
# 💡 Try `Base.decode16!` with invalid input (for example, containing 'z') to see the error.
Base.decode16!("666F6F626172")