How To Traverse Elements in Elixir

There are times when the we need to convert a list of string IDs into integer. This operations can be handled using the Enum.map to traverse and convert each element in the list by calling the Integer.parse(“some_numerical_string_value”). This function, if successful, returns a tuple in form of {some_numerical_string_value, decimal_values} or an error atom :error if otherwise. This scenerio is important when you cannot guarantee the elements in the list are integers.

However, on the case when the elements are known integers i.e values from the Database, String.to_integer can be used instead which returns the parsed integer if sucessful or throws an error if otherwise.

def convert_list_of_strings_ids_to_int do
  list = ["14", "16", "50", "25", "80"]

  Enum.map(list, fn string_id ->
    {parsed_int, ""} = Integer.parse(string_id)
    parsed_int
  end)
end

Kristian Usifoh

🖥 Software developer. React, Elixir and ExUnit

Tags
Elixir