LostKobrakai
Improving single item filters in `for`
I’m finding myself often using the following pattern with for:
for item <- listing,
result = validate_something_about_item(item),
match?({:ok, _}, result),
{:ok, data} = result do
# do something with data
end
This works, but at the same time is a super verbose way of handling the task.
It would be great to have e.g. <~ for the iterating part of for, <- to work similar to with in that it tries a pattern match an value directly (no iteration) and just goes to the next iteration if not matching:
for item <~ listing,
{:ok, data} <- validate_something_about_item(item) do
# do something with data
end
I’m aware this is not going to happen like that because it’s a breaking change. Also I wouldn’t want to propose the actually backwards compatible alternative of switching <~/<- semantic, as I feel that would further create confusion. Beginners seem to already be confused why <- does sometimes act on lists and sometimes on single items.
So I’m wondering if instead there could be something like match?(), which does however actually create bindings:
for item <- listing,
skip?({:ok, data}, validate_something_about_item(item)) do
# do something with data
end
I’d also be open to other suggestions of handling that I might not have though of.
Most Liked
Qqwy
From the documentation of for:
Generators can also be used to filter as it removes any value that doesn’t
match the pattern on the left side of <-:
So what about:
for {:ok, data} <- Enum.map(listing, &validate_something/1) do
# ...
end
Popular in Discussions
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








