Project

General

Profile

Feature #16828

Updated by sawa (Tsuyoshi Sawada) over 4 years ago

I propose to add find pattern patterns to pattern matching. 

 # Specification 
 ``` 
 find_pattern: Constant(*var, pat, ..., *var) 
             | Constant[*var, pat, ..., *var] 
             | [*var, pat, ..., *var] 
 ``` 

 This pattern is patterns are similar to array pattern, except that patterns, 
 but 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, that it doesn't support backtracking to avoid complexity, complexity. 
 This means that 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 

Back