[ruby-core:116677] [Ruby master Feature#16828] Introduce find patterns

Issue #16828 has been updated by Eregon (Benoit Daloze). An easy way to understand the "backtracking" of find pattern is it works like `each_slice(n)` and doesn't actually backtrack. So its performance is linear to the number of elements of the array being matched. https://github.com/ruby/ruby/commit/ddded1157a90d21cb54b9f07de35ab9b4cc472e1... has nice Ruby pseudo-code describing how it works. ---------------------------------------- Feature #16828: Introduce find patterns https://bugs.ruby-lang.org/issues/16828#change-106690 * Author: ktsj (Kazuki Tsujimoto) * Status: Closed * Priority: Normal * Assignee: ktsj (Kazuki Tsujimoto) ---------------------------------------- I propose to add find pattern to pattern matching. # Specification ``` find_pattern: Constant(*var, pat, ..., *var) | Constant[*var, pat, ..., *var] | [*var, pat, ..., *var] ``` This pattern is similar to array pattern, except that it finds the 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, to avoid complexity, the proposed feature doesn't support backtracking. Thus, the following code raises a 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/
participants (1)
-
Eregon (Benoit Daloze)