-
Notifications
You must be signed in to change notification settings - Fork 213
Pattern matching an element in the middle of a list. #3416
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
A list pattern checks each element pattern against a list element at a fixed position. It checks each sub-pattern only once. The destructuring takes the original object, and extracts one value, which can then be tested, bound or further destructured by a sub-pattern. What you're asking for is a search, like It's not technically impossible to add such a search feature, but it is a fourth kind of operation, different from destructuring, and quite a lot more complicated. (A linked list is not a |
I agree with @lrhn. The functionality you describe is definitely useful, and I can see us adding some kind of active-pattern-like form where users could define this themselves (#2104). But I don't think it makes sense for the built-in pattern matching syntax to have this kind of subtlety. Consider: final list = [1, 2, 3, 2, 4, 5];
if (list case [...final prefix, 2, ...final postfix]) {
print('$prefix then $postfix');
} What should that print? If the answer is "[1] then [3, 2, 4, 5]" then users will definitely request another way to get it to answer "[1, 2, 3] then [4, 5]" so we'd need some kind of "lazy rest param". And then we have to think about what happens if you mix and match those and... there's a lot of complexity there. |
@munificent wouldn't it make sense at least to have a |
IMO, It makes sense to allow any member to be used in an object pattern, not just getters. if (list case List(contains(2): true)) print("Has 2!");
if (list case List(indexOf(2): >= 0 && var i2)) print("${list.sublist(0, i2)}/${list.sublist(i2 + 1)})"); I would allow any non-assignment cascade selector as the object property selector, so also: if (json case Map(["peoples"]: Map(["victors"]: List victors))) print("All Victor's: $victors"); |
Especially for checks for Strings I was thinking about something like this: switch (message) case ['error] {
case ['acess denied'] : throw AuthenticationError();
case ['not found'] : throw NotFoundError()
} the |
I can see how to match at the start or end of a list:
I'd like to be able to match an element in the middle of a list, akin to:
Unfortunately, at most one rest element is allowed in a list or map pattern.
I can understand why this might be an issue algorithmically, but arguably matching against the end of the list could be
O(n)
if the list is a linked list.The text was updated successfully, but these errors were encountered: