HaxeDoc2

(やまだぃちぅ) #1
4 case x: x;
5 }
6 trace(node); // Leaf(foo)
Here,leafNodeis bound toLeaf("foo")if the input matches that. In all other cases,
myTreeitself is returned:case xworks similar tocase _in that it matches anything, but
with an identifier name likexit also binds the matched value to that variable.

6.4.4 Structure matching


It is also possible to match against the fields of anonymous structures and instances:
1 var myStructure ={
2 name: "haxe",
3 rating: "awesome"
4 };
5 var value = switch(myStructure){
6 case { name: "haxe", rating: "poor" }:
7 throw false;
8 case { rating: "awesome", name: n }:
9 n;
10 case _:
11 "no awesome language found";
12 }
13 trace(value); // haxe


In the second case we bind the matchednamefield to identifiernifratingmatches"awesome".
Of course this structure could also be put into theTreefrom the previous example to combine
structure and enum matching.
A limitation with regards to class instances is that you cannot match against fields of their
parent class.

6.4.5 Array matching...................................


Arrays can be matched on fixed length:
1 var myArray = [1, 6];
2 var match = switch(myArray){
3 case [2, _]: " 0 ";
4 case [_, 6]: " 1 ";
5 case []: " 2 ";
6 case [_, _, _]: " 3 ";
7 case _: " 4 ";
8 }
9 trace(match); // 1
This will trace 1 becausearray[1]matches 6 , andarray[0]is allowed to be anything.

6.4.6 Or patterns


The|operator can be used anywhere within patterns to describe multiple accepted patterns:
1 var match = switch(7) {
2 case 4 | 1: " 0 ";
Free download pdf