itssasanka
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!
Marked As Solved
NobbZ
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
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









