[ruby-core:98548] [Ruby master Feature#16828] Introduce find patterns
From:
daniel@...42.com
Date:
2020-05-27 19:07:01 UTC
List:
ruby-core #98548
Issue #16828 has been updated by Dan0042 (Daniel DeLorme).
From the implementation linked above:
```ruby
case [0, 1, 2]
in [*, a, *]
p a #=> 0; non-greedy match
end
case [0, 1, 2]
in [*, b, 2, *]
p b #=> 1; backtracking
end
```
So yes, it supports "backtracking" in a certain fashion otherwise the second case wouldn't match.
Note that it only supports splat expressions at the beginning and end of the array:
```ruby
case [0, 1, 2, 3, 4, 5, 6]
in [*, a, *, b, 5, *]
p a, b
end
# syntax error, unexpected ',', expecting ']'
# in [*, a, *, b, 5, *]
```
----------------------------------------
Feature #16828: Introduce find patterns
https://bugs.ruby-lang.org/issues/16828#change-85840
* Author: ktsj (Kazuki Tsujimoto)
* Status: Open
* Priority: Normal
----------------------------------------
I propose to add find patterns to pattern matching.
# Specification
```
find_pattern: Constant(*var, pat, ..., *var)
| Constant[*var, pat, ..., *var]
| [*var, pat, ..., *var]
```
This patterns are similar to array patterns,
but it finds first match values from the given object.
```ruby
case ["a", 1, "b", "c", 2, "d", "e", "f", 3]
in [*pre, String => x, String => y, *post]
p pre #=> ["a", 1]
p x #=> "b"
p y #=> "c"
p post #=> [2, "d", "e", "f", 3]
end
```
Note that it doesn't support backtracking to avoid complexity.
This means that the following code raises NoMatchingPatternError.
```ruby
case [0, 1, 2]
in [*, a, *] if a == 1
end
```
# Implementation
* https://github.com/k-tsj/ruby/tree/find-pattern-prototype
--
https://bugs.ruby-lang.org/
Unsubscribe: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>