chapel - 有没有办法在 Chapel 中使用 where 子句的函数中使用非标量值?

标签 chapel

在过去的一年左右的时间里,我一直在尝试Chapel。我过去曾短暂使用过 C 和 C++,但最近我的大部分经验是使用动态语言,如 Python、Ruby 和 Erlang。

在接触了 Erlang 及其函数子句之后,我很高兴发现 Chapel 中的 where 子句。但是,我在使用它们时遇到了障碍。在 Y 分钟内学习教堂包含以下代码,演示了 where 子句的使用:

proc whereProc(param N : int): void
  where (N > 0) {
    writeln("N is greater than 0");
}

proc whereProc(param N : int): void
  where (N < 0) {
    writeln("N is less than 0");
}

whereProc(10);
whereProc(-1);

这将为两个标量值 10 和 -1 中的每一个生成预期输出。但是,我尝试编写类似的程序来迭代范围或数组。我什至尝试过递归。在所有情况下,我都得到基本相同的错误:
whereproc2.chpl:12: error: unresolved call 'whereProc(int(64))'
whereproc2.chpl:1: note: candidates are: whereProc(param N: int)
whereproc2.chpl:6: note:                 whereProc(param N: int)

产生此特定错误的代码是:
proc whereProc(param N : int): void
  where (N > 0) {
    writeln("N is greater than 0");
}

proc whereProc(param N : int): void
  where (N <= 0) {
    writeln("N is less than or equal to 0");
}

for n in 1..10 do
  whereProc(n);

是否有我遗漏的东西会导致它起作用,或者这不会起作用?我注意到在 Y 分钟内学习教堂它说所有信息都需要在编译时知道。有限范围或初始化数组的内容在编译时是否未知?在我看来,如果 where 子句仅适用于标量值,则它的用处是有限的。

最佳答案

Is there something I'm missing that will cause this to work...?



是的,问题在于您的 for环形:
for n in 1..10 do
  whereProc(n);

迭代范围时,循环索引变量 n是一个执行时常量,它可以防止编译器对其进行推理。为了获得您想要的行为,您需要请求编译器将其设为 param (编译时常量)。这可以使用以下语法完成:
for param n in 1..10 do
  whereProc(n);

这具有制作n的效果param value 使编译器能够推理其值。 Try this version of the code online (有一个更有趣的范围)。

使用像这样的参数索引表达式可以被视为完全展开循环:
{
  param n = 1;
  whereProc(n);
}
{
  param n = 2;
  whereProc(n);
}
...
{
  param n = 10;
  whereProc(n);
}

因此,当类型可能从一次迭代到下一次迭代(如异构元组)时,这可能是迭代事物的有用习惯用法。

关于chapel - 有没有办法在 Chapel 中使用 where 子句的函数中使用非标量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49991190/

相关文章:

io - C fgets 函数的等效 Chapel 功能

arrays - Chapel:内存中的数组数组与 2 维数组

json - 如何从 Chapel 中的记录返回 JSON 字符串?

chapel - 是否可以生成映射 Distribution 的 Locales 网格?

simulation - 相当于 Chapel 中 Octave 的 `meshgrid`

chapel - Chapel中的增量编译

string-formatting - 如何格式化 Chapel 中的字符串输出?

sparse-matrix - Chapel 循环变量未声明

chapel - 如何在教堂中保留可接受类型的列表以进行比较

nvidia - 使用 Chapel 使用两个 Nvidia Jetson nano 开发工具包时遇到问题