How to split an integer into its parts using Elixir


Percy Grunwald's Profile Picture

Written by Percy Grunwald

— Last Updated February 25, 2019

Table of Contents

A common problem in a lot of programming languages is how to split an integer into its parts – e.g. 1234 => [1, 2, 3, 4]. It’s pretty quick and easy to do this in Elixir and it’s a technique I used to solve the Roman Numerals problem in Exercism Elixir.

Here’s the code I came up with:

defp split_integer(int) do
  int
  |> Kernel.to_string()
  |> String.split("", trim: true)
  |> Enum.map(fn int_string ->
    Integer.parse(int_string)
    |> case do
      {int, _} ->
        int

      _ ->
        0
    end
  end)
end

Here’s an explanation of the data flow in the function:

  1. Convert the integer into a string 1234 => "1234"
  2. Split up all the characters in the string "1234" => ["1", "2", "3", "4"]
  3. Parse each string in the list back into an integer, defaulting to 0 if the item isn’t a valid string representation of an integer ["1", "2", "3", "4"] => [1, 2, 3, 4]

That’s it! Can you think of any other ways to do it? Would love to see your solution as well, please hit me up in the comments below.

Comment & Share