Discussion: indexer patterns #4889
Unanswered
alrz
asked this question in
Language Ideas
Replies: 2 comments 5 replies
-
Would this bind to the Countable pattern or TryGetValue for |
Beta Was this translation helpful? Give feedback.
4 replies
-
While I get where you're coming from with the variable references as "pseudo-constants", I don't think that's appropriate to allow as part of this proposal. It will effectively force us to solve the exhaustiveness problem that introducing any non-constant expression into patterns would create. While I'm not necessarily opposed to such a change, I think it needs to be a separate proposal and not part of this one. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
While list-patterns cover this use case to some extend, they get too verbose when patterns are not sequential, such as matching the nth element.
e is [ _, _, _, pat ]
Indexer patterns would be an addition to property subpatterns:
Any non-empty list of constant expressions may be used as the indexer arguments.
If the type is countable and indexable, we emit the length check depending on the argument.
Otherwise, we bind a
TryGetValue(T, out V)
instance method.--
To make this more useful, we need to accept non-constants inside patterns.
The following "pseudo-constants" could be permitted as the indexer argument:
^e1
where e1 is a pseudo-constante1..e2
where e1 and e2 are pseudo-constantstypeof(T)
This permits a safe collection access with a non-constant indexer argument:
Range expressions are special here because we can deduce a minimum length based on the value.
These expressions will be inlined inside the invocation, so they may be evaluated multiple times. That is, we don't capture such expressions in a temp. That's why we need to make sure these expressions are side-effect free.
--
The same concept can be applied to patterns themselves, permitting:
Since we're matching the value rather than just passing it, we need to distinguish between value and reference equality.
Matching by value: Using the same semantic as auto-generated record
Equals
method.case { Prop: obj } // EqualityComparer<T>.Default.Equals(e.Prop, obj)
Matching by reference: Allow to ditch value semantics and use a simple reference comparison.
case { Prop: ref obj } // object.ReferenceEquals(e.Prop, obj)
This permits more complex argument validation using pattern matching which is currently limited to constants.
Beta Was this translation helpful? Give feedback.
All reactions