haxe案例模式重用 - 可能作为变量

cso*_*akk 1 haxe pattern-matching

有没有办法在haxe中保存模式?我有几个开关函数,其中一些具有相同的模式,为了使代码更清晰,我想将它们保存到一个公共数组或其他东西.所以我有类似的东西

switch (field) {
     case 'x' | 'y' | 'color' : doThis();
} 
//...other function...
switch (field) {
     case 'x' | 'y' | 'color' : doThat();
}
Run Code Online (Sandbox Code Playgroud)

我希望有类似的东西

myPattern = 'x' | 'y' | 'color';

switch (field) {
     case myPattern : doThis();
} 
//...other function...
switch (field) {
     case myPattern : doThat();
}
Run Code Online (Sandbox Code Playgroud)

And*_* Li 5

您可以使用提取器.

class Test {
    static function myPattern(str:String):Bool {
        return switch (str) {
            case 'x' | 'y' | 'color':
                true;
            case _:
                false;
        }
    }
    static function main():Void {
        var field = "x";
        switch (field) {
            case myPattern(_) => true:
                trace('myPattern');
            case _:
                trace('$field is not myPattern');
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

只有一个方面:当使用提取器时,穷举检查无法发现提取器中匹配的模式:

enum MyEnum
{
    A;
    B;
    C;
}

class Test {
    static function ab(str:MyEnum):Bool {
        return switch (str) {
            case A | B:
                true;
            case _:
                false;
        }
    }
    static function main():Void {
        var field = A;
        switch (field) {
            case ab(_) => true:
                trace('A|B');
            case C:
                trace('$field is not A|B');
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

会导致错误:

Test.hx:19: characters 10-15 : Unmatched patterns: B | A
Test.hx:19: characters 10-15 : Note: Patterns with extractors may require a default pattern
Run Code Online (Sandbox Code Playgroud)

如果发生这种情况,只需case _:在最后添加一个就可以了.