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

0

I tried to get it in the traditional way: [:a, :b, :c, :d][2] however 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
    
asked by anonymous 17.02.2018 / 19:55

1 answer

1

Elixir is not an object-oriented language, so the Enum module has only three functions that allow you to access 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 indices that do not exist, you will have 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: link

    
17.02.2018 / 19:55