LostKobrakai

LostKobrakai

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.

Showing Posts 1 to 5

al2o3cr

al2o3cr

This seems to do what you’re looking for:

# NOTE: the only part of this that's important is returning {:ok, _} vs {:error, _}
defmodule Validator do                                  
  def validate(<<x::binary-size(3)>>), do: {:ok, String.upcase(x)}  
  def validate(x), do: {:error, x}
end

a = ["foo", "bar", "mumble"]

for x <- a, {:ok, arg} <- [Validator.validate(x)], do: arg        
# returns ["FOO", "BAR"]
LostKobrakai

LostKobrakai OP

While this does work, wrapping things in a list just to pull it directly out again kind feels wrong.

Qqwy

Qqwy

TypeCheck Core Team

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
LostKobrakai

LostKobrakai OP

Another possible workaround, but it will result in one more iteration over the list.

for i <- 1..10, rem(i, 2) == 1, do: i

This will iterate only once filtering out the odd i’s. E.g. Enum.filter_map has been deprecated with the hint of using for instead.

Qqwy

Qqwy

TypeCheck Core Team

Very interesting!
I did a couple of tests by writing the same function multiple times in different styles (Enum, for and :lists; I did not check Erlang’s list comprehensions) and see what kind of bytecode they would compile down to.

The conclusion is that for seems oddly enough to be slightly more optimized in that the body of the for-loop is inlined.

It also means that currently the BEAM does not perform any kind of list fusion. This is an optimization that might be added to the compiler in the future for sure, as it is relatively straightforward.


Something to think about right now is if you should care for most application code about traversing a list twice. If the list is short the difference is negligible. If the list is long, you probably are better off using Stream instead anyway. I’d suggest to opt for a pipeline of Enum-functions until profiling/benchmarking shows that that particular piece of code is too slow for what it is intending to do, at which time it could be rewritten with direct calls to the functions in the:lists module or potentially manual recursion.

I also would like to point out that the current warning that is shown when you are using Enum.filter_map is

Enum.filter_map/3 is deprecated. Use Enum.filter/2 + Enum.map/2 or for comprehensions instead

, hinting at no particular preference of either for or Enum.

— All posts loaded —

Where Next? Top

Trending in Discussions Top

AstonJ
As the title says, please share what you’ve been up to with Elixir. Whether that’s been learning it, looking into it, making stuff with i...
2977 92995 915
New
AstonJ
The obligatory hello world thread! Who are you and where are you from? :stuck_out_tongue:
4616 55835 594
New
caslu
I want to open this thread for you all to discuss and help those who really like Ash but are still hesitant to use it in a real project. ...
New
arcanemachine
I was working on an Ecto migration and I needed a timestamp. So, for the nth time, I looked up the different data types for timestamps, a...
New
alexslade
Fly’s CEO posted this recently - Turn And Face The Strange · The Fly Blog It says that Fly is going all-in on sprites, which is a worry ...
New
Herve37
We’re evaluating API mocking tools for OpenAPI-based projects and would love to hear what other teams are using. We’re particularly inte...
New
matt-savvy
Is there a word for the ~> symbol used in Version strings? Do you also just call it a Squiggle Arrow™ ?!
New

Other Trending Topics Top

garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New
aseigo
ICal is a library for interacting with iCalendar data. It parses iCalendars into typed Elixir structs via ICal.from_ics, and can prepare ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews