Today I Learned

hashrocket A Hashrocket project

Accessing a single element of a list by index

Getting an element from a list using an index is a common language idiom.

In ruby you would use the squares [] method (similar to Java, C#, etc.).

> [:a, :b, :c, :d][2]
:c

But Elixir is not object oriented and instead provides the Enum module that has many functions that can operate on a list. Three functions return an element by index.

iex > Enum.at([:a, :b, :c, :d], 2)
:c
iex > Enum.fetch([:a, :b, :c, :d], 2)
{ :ok, :c }
iex > Enum.fetch!([:a, :b, :c, :d], 2)
{ :ok, :c }

They behave differently when the index doesn't correspond to the list.

iex > Enum.at([:a, :b, :c, :d], 9999)
nil
iex > Enum.fetch([:a, :b, :c, :d], 9999)
:error
iex > Enum.fetch!([:a, :b, :c, :d], 9999)
** (Enum.OutOfBoundsError) out of bounds error
    (elixir) lib/enum.ex:722: Enum.fetch!/2

I don't understand how the statuses (:ok, :error) might be used in application code yet by I'm curious and can't wait to find out!

See More #elixir TILs
Looking for help? At Hashrocket, we 💜 Elixir! From our many Elixir client projects, to sponsoring the Chicago Elixir Meetup, to the source code for this application, we are invested in this community. Contact us today to talk about your Elixir project.