HaxeDoc2

(やまだぃちぅ) #1

7 static public function main() {
8 var e = TString("fOo");
9 switch(e){
10 case TString(temp):
11 switch(temp.toLowerCase()) {
12 case "foo": true;
13 case : false;
14 }
15 case
: false;
16 }
17 }
18 }


Here we have to capture the argument value of theTStringenum constructor in a variable
tempand use a nested switch ontemp.toLowerCase(). Obviously, we want matching to
succeed ifTStringholds a value of"foo"regardless of its casing. This can be simplified with
extractors:
1 enum Test {
2 TString(s:String);
3 TInt(i:Int);
4 }
5
6 class Main {
7 static public function main() {
8 var e = TString("fOo");
9 var success = switch(e){
10 case TString(.toLowerCase() =>"foo"):
11 true;
12 case
:
13 false;
14 }
15 }
16 }


Extractors are identified by theextractorExpression => matchexpression. The com-
piler generates code which is similar to the previous example, but the original syntax was greatly
simplified. Extractors consist of two parts, which are separated by the=>operator:

1.The left side can be any expression, where all occurrences of underscore_are replaced with
the currently matched value.

2.The right side is a pattern which is matched against the result of the evaluation of the left
side.

Since the right side is a pattern, it can contain another extractor. The following example
“chains” two extractors:
1 class Main {
2 static public function main() {
3 switch(3) {
4 case add(_, 1) => mul(_, 3) =>a:
5 trace(a);
6 }
Free download pdf