Skip to content

Pattern Matching

Ígor Bonadio edited this page Jun 9, 2015 · 2 revisions

Pattern Matching

  • We only can match tuples
  • Other objects can implement a tuple() method to convert them into tuples

Grammar:

match : `match` expression case+ `end`
      ;

case : `case` case_lhs+ `=>` expressions
     ;

case_lhs : '(' case_exprs ')'
         ;

case_exprs : case_expr
           | case_exprs ',' case_expr
           ;

case_expr : ID
          | literal
          | bool_expr
          ;

Examples:

match tuple
  case ("Square" or "Rectangle", a, b) => a*b
  case (n <= 0 or n >= 10, _)          => 1
  case (a <= 0, _)                     => 3
  case (_, b<= 0)                      => 4
end

match tuple
  case (a <= 0, b)
       (a, b <= 0) => 0
end

Clone this wiki locally