Extension types and type-testing for active patterns #8182
Replies: 2 comments 3 replies
-
Extension methods for user-defined positional patterns would be interesting. There have been conversations on Discord recently that the team is very interested in having pattern matching work with extensions. In that case it has been more of a question of matching the underlying type to the extension type where you'd want to apply some validation. In this situation the pattern would behave more like a type pattern, but at that point I don't see why normal deconstruction wouldn't work. More interestingly would be what kind of changes would be required in the language to enable inputs to patterns. That's something I've hoped would be added to support general purpose active patterns, like regex. |
Beta Was this translation helpful? Give feedback.
-
I guess that hinges on what it means to have a constructor for an extension type: public extension MatchRegex(string pattern) for string
{
public bool Deconstruct(out object[] captures)
{
// Impl not important for this example, but uses the pattern constructor parameter
...
}
} And then, at the risk of bike-shedding, we maybe have something like: switch (s)
{
case MatchRegex("a(b)c")(captures):
Console.WriteLine(captures[0]);
break;
...
} where |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Apologies if the title is confusing, but I'm wondering if we can leverage roles/extensions with pattern matching to get, effectively, active patterns.
Here's what I mean; the language has, to an extent, painted itself into a syntactic corner a little bit around pattern matching and deconstruction, in that deconstruction currently cannot fail without throwing an exception and it's not possible to have named deconstructors, since deconstruction requires the name of the method be
Deconstruct
. This means an entirely new construct will have to be developed to implement active patterns (i.e. patterns that the user can define and have control over both deconstruction and whether or not the patterns succeeds or fails).If the language expands pattern matching slightly so that
Deconstruct
can return abool
, that at least allows us to define fallible patterns. We might then be able to use roles to fill in the presence of named deconstructors, e.g.I think this fits quite well since
MatchRegex
is a type name and it goes in the pattern syntax where a type would normally be:if (s is MatchRegex(".+") captures)
. Let me know your thoughts.Beta Was this translation helpful? Give feedback.
All reactions