Vibbiz
Vibbiz

Reputation: 21

Break down integers greater than 10 into its components from an elixir list

How do I take a list of say [1,2,3,45,67,] and break it down to [1,2,3,4,5,6,7]?

Upvotes: 1

Views: 68

Answers (3)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Using Kernel.SpecialForms.for/1 comprehension.

for << <<c>> <- Enum.join([1, 2, 3, 45, 67]) >>, do: c - ?1 + 1
#⇒ [1, 2, 3, 4, 5, 6, 7]

Upvotes: 0

Guru Stron
Guru Stron

Reputation: 141665

You can try something like this:

[1, 2, 3, 45, 67] 
|> Enum.map(&Integer.to_string/1) 
|> Enum.flat_map(&String.graphemes/1)
|> Enum.map(&String.to_integer/1) # results in [1, 2, 3, 4, 5, 6, 7]

Upvotes: 0

zwippie
zwippie

Reputation: 15515

It can be done without string conversion:

Enum.flat_map([1, 2, 3, 45, 67], &Integer.digits/1)

Upvotes: 5

Related Questions