How to pick an element from a list by index in Elixir

Asked

Viewed 218 times

1

I tried to take it the traditional way: [:a, :b, :c, :d][2] but I get the following error:

** (ArgumentError) the Access calls for keywords expect the key to be an atom, got: 2
(elixir) lib/access.ex:255: Access.fetch/2
(elixir) lib/access.ex:269: Access.get/3

1 answer

2


Elixir is not an object-oriented language, so the module Enum has only three functions that allow accessing an element of an array based on its 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 }

If you try to access non-existent indices, you will get a different result for each function:

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

Source: https://til.hashrocket.com/posts/633ba08446-accessing-a-single-element-of-a-list-by-index

Browser other questions tagged

You are not signed in. Login or sign up in order to post.