Project

General

Profile

Actions

Feature #16828

closed

Introduce find patterns

Added by ktsj (Kazuki Tsujimoto) over 4 years ago. Updated 9 months ago.

Status:
Closed
Target version:
-
[ruby-core:98131]

Description

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.

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.

case [0, 1, 2]
in [*, a, *] if a == 1
end

Implementation

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0