Make assignment (match) in comprehension work as strict generator #9153
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
It would be useful to be able to easily bind variables in the qualifiers of a comprehension, for example:
You can do this today by writing a singleton generator:
but this has some drawbacks: the intent is not clear to the reader; you have to remember to write a single element list around the right hand side argument (which itself could be a list); you probably want it to be a strict generator so typos don't just silently yield no elements; and someone might edit the code later and accidentally add extra elements to the right hand side, causing unintended Cartesian combinations.
It is in fact already allowed syntactically to have a
=
match expression in the qualifiers, but this is just interpreted as any other expression - thus expected to produce a boolean value, and if false, the current element will be skipped. Hence, any qualifier to the right of aV = Expr
match will only execute if V is true. We can therefore expect that no such uses exist in practice. (The OTP code base has been checked and does not contain any.) To be completely safe, matches in a comprehension qualifier position can first be made an error, and then allowed with these binding semantics in the following major release.This is related but orthogonal to #9134. It would make those few cases where variables have been exported from subexpressions of qualifiers much nicer to rewrite than requiring them to be singleton generators.