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

时间:2014-12-29 16:27:55

标签: pattern-matching haxe

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

的东西
switch (field) {
     case 'x' | 'y' | 'color' : doThis();
} 
//...other function...
switch (field) {
     case 'x' | 'y' | 'color' : doThat();
}

我想要像

这样的东西
myPattern = 'x' | 'y' | 'color';

switch (field) {
     case myPattern : doThis();
} 
//...other function...
switch (field) {
     case myPattern : doThat();
}

3 个答案:

答案 0 :(得分:5)

您可以使用extractor

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');
        }
    }
}

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

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');
        }
    }
}

会导致错误:

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

如果发生这种情况,只需在最后添加case _:即可。

答案 1 :(得分:1)

您无法以您希望的方式存储图案。编译器在编译时执行某些工作,无法优化仅在运行时可用的模式。你可以做的是扭转模式:

function evaluate(test : String , patternA : Void-> Void, patternB : Void -> Void) {
  switch test {
    case 'x' | 'y' | 'color' : patternA();
    case _ : patternB(); 
  }
}

当然我不知道你想要达到的目标,因此很难提供更好的答案。

答案 2 :(得分:1)

您也可以(我相信这是最干净的方式)使用一个开关将您的值转换为精确代表您需要的案例的枚举,并在以后使用简单且更易读的开关。