如何在 Chapel 中编写模板函数的类型签名

How to write the type signature of a template function in Chapel

在尝试编写算术平均函数时,最好编写一个模板函数而不是两个特定类型的函数。可以这样写: proc mean(data: [?] ?T): real 但是如何将 T 限制为 intreal.

是否可以定义一个可以包含 intreal 数据的数组,即是否有表达数组内容联合类型的方法?

要将 T 的类型限制为任何大小的 intreal 类型,您可以在函数定义中添加 where 子句:

proc mean(data: [] ?T): real where isIntType(T) || isRealType(T) { ... }

isIntTypeisRealType函数定义在Types模块中:http://chapel.cray.com/docs/latest/modules/standard/Types.html

Chapel 支持安全联合和联合数组。联合在 Chapel 语言规范的第 17 节中进行了描述:http://chapel.cray.com/docs/latest/_downloads/chapelLanguageSpec.pdf

union IntOrReal {
  var i: int;
  var r: real;
}

var intRealArray: [1..2] IntOrReal;
intRealArray[1].i = 1;
intRealArray[2].r = 2.0;