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!)

2 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