💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
**Haxe 3.1.0以后** > **Since Haxe 3.1.0** 提取器允许应用变换到被匹配的值。这才需要对一个匹配的值在匹配继续之前做一个小的操作时经常用到: > Extractors allow applying transformations to values being matched. This is often useful when a small operation is required on a matched value before matching can continue: ~~~ enum Test { TString(s:String); TInt(i:Int); } class Main { static public function main() { var e = TString("fOo"); switch(e) { case TString(temp): switch(temp.toLowerCase()) { case "foo": true; case _: false; } case _: false; } } } ~~~ 这里我们需要TString 枚举构造器的参数值到一个变量 temp,并使用一个嵌套的 switch到temp.toLowerCase() 。很明显,我们想要匹配如果TString保存一个无论大小写的“foo”则成功。这可以通过提取器简单实现: > Here we have to capture the argument value of the TString enum constructor in a variable temp and use a nested switch on temp.toLowerCase(). Obviously, we want matching to succeed if TString holds a value of "foo" regardless of its casing. This can be simplified with extractors: ~~~ enum Test { TString(s:String); TInt(i:Int); } class Main { static public function main() { var e = TString("fOo"); var success = switch(e) { case TString(_.toLowerCase() => "foo"): true; case _: false; } } } ~~~ 提取器通过extractorExpression => match 表达式识别。编译器生成的代码类似于前面的例子,但是原生的语法被大大精简。提取器由两部分组成,被 => 操作符分隔: > Extractors are identified by the extractorExpression => match expression. The compiler 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: * 左侧可以使任何的表达式,中间出现的所有下划线被替换为当前匹配的值。 * 右侧是一个模式,匹配的左侧执行的结果。 > * The left side can be any expression,where all occurrences of underscore_are replaced with the currently matched value. > * 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: ~~~ class Main { static public function main() { switch(3) { case add(_, 1) => mul(_, 3) => a: trace(a); } } static function add(i1:Int, i2:Int) { return i1 + i2; } static function mul(i1:Int, i2:Int) { return i1 * i2; } } ~~~ 这里输出 12 作为调用 add(3,1)的结果,3是匹配的值,mul(4,3)中4是add调用的结果。需要注意的是,a在第二个 =>操作符的右侧是一个捕获的变量(第6.4.3节)。 > This traces 12 as a result of the calls to add(3, 1), where 3 is the matched value, and mul(4, 3) where 4 is the result of the add call. It is worth noting that the a on the right side of the second => operator is a capture variable (6.4.3). 当前不能在 or 模式中使用提取器: > It is currently not possible to use extractors within or-patterns (6.4.6): ~~~ class Main { static public function main() { switch("foo") { // Extractors in or patterns are not allowed case (_.toLowerCase() => "foo") | "bar": } } } ~~~ 然而,可以把or模式用在提取器的右侧,所以前面的例子会编译而没有括号。 > However, it is possible to have or-patterns on the right side of an extractor, so the previous example would compile without the parentheses.