Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does | (pipe) in pattern matching work?

You can write:

str match { case "foo" | "bar" => ... } 

At first glance it looks like | could be an extractor object, however:

str match { case |("foo", "bar") => ... } 

does not work. (And I can't see how that could be implemented anyway.)

So it is a magic built-in operator?

(I believe I have seen this question on SO before, but it's impossible to search for...)

like image 735
Knut Arne Vedaa Avatar asked Jun 26 '11 13:06

Knut Arne Vedaa


People also ask

What is in pattern matching?

Pattern matching in computer science is the checking and locating of specific sequences of data of some pattern among raw data or a sequence of tokens. Unlike pattern recognition, the match has to be exact in the case of pattern matching.

How the second pattern matching will work?

The second algorithm uses a table which is derived from pattern PAT independent of TEXT. The pattern matching table F(Q,TEXT) of pattern PAT is in memory. The input is an N character string TEXT=T1, T2,…, Tn. This algorithm finds INDEX(PAT) in TEXT.

What is pattern matching in code?

Pattern matching is a technique where you test an expression to determine if it has certain characteristics. C# pattern matching provides more concise syntax for testing expressions and taking action when an expression matches.


1 Answers

| is not implemented in the library, it is interpreted by the Scala compiler. It builds a new pattern that is defined as the disjunction between two subpatterns that don't bind any variable (although the newly formed pattern can itself be bound; i.e., you can write stuff like

try { /*...*/ } catch {   case e @ (_: IOException | _: IllegalArgumentException) => /*...*/ } 

and e gets as type the most specific supertype of the listed alternatives).

like image 73
Jean-Philippe Pellet Avatar answered Sep 29 '22 18:09

Jean-Philippe Pellet