Powered by AppSignal & Oban Pro

Lists and Tuples

02-lists-and-tuples.livemd

Lists and Tuples

Mix.install([
  {:kino, "~> 0.14.0"}
])

Lists

We create lists with [] Actually we created a list in previous examples

orders = [1, 70, 110]

We can store mixed values in a List

my_school_bag = ["pens", 11, :rock, :pencil_box, "books", 55.7, true]

List manipulation

We are using ++ to concatenate lists.

[:clay] ++ my_school_bag

We can use -- to subsctract from a list

my_school_bag -- [:rock]

The result is a new list, it never modifies the original

In elixir Data Structures are Immutable, means we never modifies the original

Don’t worry BEAM VM, Elixir’s VM is smart enough to handle this in an efficient way

# so it means my_school_bag is unchanged

my_school_bag

Prepending

[:water_bottle | my_school_bag]

Appending

my_school_bag ++ [:water_bottle]

Immutability in action 💪

my_school_bag = ["pens", 11, :rock, :pencil_box, "books", 55.7, true]
extra_books = ["Sherlock Holmes", "Robin Hood"]

bag = my_school_bag ++ extra_books

Original data is not modified

my_school_bag
extra_books

We get a new list instead

bag

There are special modules in Elixir to make your life easier

Enum and List modules can help you manipulate lists

Enum.at(bag, 3)
List.replace_at(bag, 1, "atlas pens")

If we check bag its still unchanged

bag

So its immutable 🫢

Tuples

Tuples are created using {}

Do NOT confuse this with a object in JS

{"gandalf", "frodo", "sam", "tom bombadil", :sauron}

Often we use this with functions to return multiple values

{:ok, "Here are some details you like"}

For example lets try to read a File

content =
  Kino.FS.file_path("random_names.csv")
  |> File.read()

Here you can see it has returned a tuple with {:ok, "content"} format

File.read("404.txt")

In here you can see we have {:error, reason} tuple

There are functions like put_elem, elem also Tuple module for dealing with tuples… Most of the time you wont use them…but good to know 🤓