Combine some list element pairs based on a condition?

Hi, I have a list like this

["blah", "12", "blaaa", "hello", "13"....]
Basically, some elements are numbers and others are normal strings. The list is always going to start with alphabetical strings.

What I want to do is, if a number precedes a string, join them both. Otherwise, keep the elements as it is.

For the example above, I need the output to be:
["blah12", "blaaa", "hello13"....]

I looked at chunk_while on the Enum protocol, but not really sure if it can serve this purpose. While I can do manual Enum.map along with parsing each element separately while dropping and reinserting items, I’m looking for a more elegant way. I’m pretty positive there is some API I can use either on the List or Enum to achieve my result.

Can someone throw some insight please! Thank you and will really appreciate your help!

You could use Enum.reduce/3 roughly like this:

input
|> Enum.reduce([], fn
  s, [] -> [s]
  s, [h|t] -> case Integer.parse(s) do
    {_, ""} -> [h <> s|t]
    _ -> [s, h|t]
  end
end)
|> Enum.reverse
5 Likes

Thank you! that works! By any chance, is there any API we can directly leverage for this?