[英]Apply a function on array of values inside Haxe macro
我在Haxe宏中生成一個Int
數組,並想在其上應用一個函數,如下所示:
typedef ComponentIdArray = Array<Int>;
class MyMacros {
// Each descendant of 'Component' has static member 'id_'
// Convert array of classes to corresponding indices
public static macro function classesToIndices(indexClasses:Array<ExprOf<Class<Component>>>) {
var ixs = [for (indexClass in indexClasses) {macro $indexClass.id_ ;}];
return macro $a{ixs};
}
public static macro function allOf(indexClasses:Array<ExprOf<Class<Component>>>) {
var indices = macro Matcher.classesToIndices($a{indexClasses});
// FIXME
// FIXME 'distinct' is a function from thx.core -- DOES NOT WORK
//var indices2 = macro ($a{indices}.distinct());
return macro MyMacros.allOfIndices($indices);
}
public static function allOfIndices(indices:ComponentIdArray) {
trace(indices);
//... normal function
// currently I call indices.distinct() here
return indices.distinct();
}
}
用法:
class C1 extends Component {} // C1.id_ will be set to 1
class C2 extends Component {} // C2.id_ will be set to 2
var r = MyMacros.allOf(C1, C2, C1); // should return [1,2]
因為編譯時一切都是已知的,所以我想在宏中執行此操作。
KevinResoL的答案基本上是正確的,除了你似乎想要在編譯時執行distinct()
(正如你在try.haxe的輸出選項卡中看到的那樣,生成的JS代碼包含thx.Arrays.distinct()
調用)。
最簡單的解決方案可能就是在allOf()
中allOf()
調用distinct()
allOf()
:
using haxe.macro.ExprTools;
public static macro function allOf(indexClasses:Array<ExprOf<Class<Component>>>) {
indexClasses = indexClasses.distinct(function(e1, e2) {
return e1.toString() == e2.toString();
});
var indices = macro Matcher.classesToIndices($a{indexClasses});
return macro MyMacros.allOfIndices($indices);
}
如您所見,您還需要為distinct()
定義自定義predicate
,因為您正在比較表達式 - 默認情況下它使用簡單的相等性檢查( ==
),這不夠好。
生成的代碼如下所示(如果id_
變量是inline
聲明的):
var r = MyMacros.allOfIndices([1, 2]);
.distinct()
僅在調用函數的模塊中using thx.Arrays
時可用。 使用宏生成表達式時,無法保證調用點具有using
位置。 所以你應該使用靜態調用:
這適用於您的代碼:
public static macro function allOf(indexClasses:Array<ExprOf<Class<Component>>>) {
var indices = macro Matcher.classesToIndices($a{indexClasses});
var e = macro $a{indices}; // putting $a{} directly in function call will be reified as argument list, so we store the expression first
return macro thx.Arrays.distinct($e);
}
另請參閱這個有關haxe的工作示例: http ://try-haxe.mrcdk.com/#9B5d6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.