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

cblavier
Hey there, It’s been more than a year since we started using LiveView as our main UI library and building a whole library of UI componen...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
achempion
I’ve been using Emacs as my main code editor for more than a two years. It’s a custom build version although I’ve tried doom emacs and sp...
New
axelson
Hi there! :wave: @frigidcode and I (but mostly him) have been running an Elixir Book club, we’re almost done with Designing Elixir Syste...
New
budgie
I love Elixir. It’s one of 2 programming languages I’ve ever fallen in love with. But I don’t use it anymore. Serverless was the promis...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
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
georgeguimaraes
Just published claude-code-elixir, a plugin marketplace for Claude Code with Elixir support. These are the plugins I’ve been using for my...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews