Skip to content
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

Discussion: slice patterns #1510

Closed
alrz opened this issue May 11, 2018 · 2 comments
Closed

Discussion: slice patterns #1510

alrz opened this issue May 11, 2018 · 2 comments

Comments

@alrz
Copy link
Member

alrz commented May 11, 2018

This would be an increment on the "list pattern" proposal (#1039)

static bool IsSymmetric(Span<int> list) {
  switch (list) {
    case []:
    case [_]:
      return true;
    case [var first, ..var others, var last] when first == last:
      return IsSymmetric(others);
    default:
      return false;
  }
}

->

static bool IsSymmetric(Span<int> list) {
  int length = list.Length;
  if (length == 0 || length == 1) {
    return true;     
  }

  int first = list[0];
  int last = list[^1];
  Span<int> others = list[1..^1]; 
  if (first == last) {
    return IsSymmetric(others);
  }

  return false;
}
  • The .. expansion should work with any type with a range indexer.
  • The resulting type of .. expansion would be the return type of the indexer, e.g. Span<int> here.
  • Only a single .. expansion would be allowed in the pattern.
  • As mentioned in [Discussion] Revisiting pattern matching on collections #1039, we may use .. as an standalone pattern to skip elements.
if (collection is [.., 99, 100]) 
    // matches on the last two elements only

if (collection is [1, 2, ..]) 
    // matches on the first two elements

if (collection is [1, .., 100]) 
    // matches the first and last elements
@ufcpp
Copy link

ufcpp commented May 11, 2018

Can the following pattern substitute this proposal to some extent?

    public static bool Deconstruct<T>(this Span<T> x, out T first, out Range range, out T last)
    {
        first = x[0];
        range = ..;
        last = x[^2];
    }
if (collection is (1, .., 100))

@alrz
Copy link
Member Author

alrz commented May 11, 2018

@ufcpp I'd say that would be a very limited helper, to only match first and last element. Note that the slice pattern could appear anywhere in the list pattern (first, last, or anywhere in between). Consider a list pattern with more that one element to match. You'd need N Deconstruct overloads to make that work, and still since all Deconstruct overloads must differ in parameter counts, you'd be limited to a particular set of overloads.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants