List comprehension with for has a behaviour I do not understand

I was using a for loop while matching on a pattern something like this

for {a,b, _} <- my_list do
...
end

And I noticed that this was not running as I thought and the reason was because the structure didn’t match. I instead needed to do

for {a,b} <- my_list do
...
end

Now while I am glad I figured that out, my question is why does the wrong version return []. And is there a way this should have raised an error when it couldn’t match what I was looking for?

That is the correct behaviour of list comprehensions. Like with with, the <- operator is essentially a version of = that doesn’t raise when there is no match. You need to keep this in mind when using comprehensions. If you want to be strict, you need to use an Enum function (I’ve been burned by this before too!)

3 Likes

I did not know this. Thank you!! Clears up a lot of the confusion I was having. Changed the function to use Enum instead.

1 Like

Hi,
to complete the discussion, erlang has quite recently added strict generators that would do what you were expected initially :

Maybe this will be ported to elixir at some time in the future :slight_smile:
Anyway, the doc explain the difference and erlang was only supporting relaxed generators for a very long time.

Edit : to complete my post, here is the EEP that has proposed strict generators:

Cheers,

Sébastien.

2 Likes

This is interesting! Hopefully it will be ported to Elixir soon.