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