Chapel语言带元组解包的过程哑参用法及性能疑问
关于Chapel中元组参数解包的疑问与性能/可读性探讨
在BenchmarksGame网站的nbody程序中,我注意到sumOfSquares()采用了如下写法:
// compute the sum of squares of a 3-tuple's elements inline proc sumOfSquares((x,y,z)) { return x**2 + y**2 + z**2; }
我疑惑上述哑参(x,y,z)的写法是否类似“元组解包”,效果等同于:
var (x,y,z) = {调用端的实际元组};
为验证这一点,我编写了测试代码,发现实际元组t是以传值方式传入myproc((x,y,z)),且子例程中可修改各分量。具体而言,我认为下面代码中的(1)和(2)含义相似,(2)和(3)除了解包外功能基本一致,请问该理解是否正确?
测试代码:
var t_orig = (1.0, "hello"); var t = t_orig; writeln("t = ", t); var (x,y) = t; // (1) x = 100; y = "hi"; writeln("x = ", x, " y = ", y, " t = ", t); // t -> (1.0, "hello") ref (p,q) = t; // (1') p = 100; q = "hi"; writeln("p = ", p, " q = ", q, " t = ", t); // t -> (100.0, "hi") proc myproc((x, y)) // (2) { x += 1.0; y += " world"; writeln("myproc(): ", (x,y)); } proc myproc2(in u) // (3) // proc myproc2(ref u) // t -> (2.0, "hello world") // proc myproc2(inout u) // t -> (2.0, "hello world") // proc myproc2(u) // (4) error: 'u' is const and cannot be modified { u[0] += 1.0; u[1] += " world"; writeln("myproc2(): ", u); } t = t_orig; myproc(t); // (2.0, "hello world") writeln("t = ", t); // (1.0, "hello") t = t_orig; myproc2(t); writeln("t = ", t); // depends on routines
运行结果(来自ATO):
t = (1.0, hello) x = 100.0 y = hi t = (1.0, hello) p = 100.0 q = hi t = (100.0, hi) myproc(): (2.0, hello world) t = (1.0, hello) myproc2(): (2.0, hello world) t = (1.0, hello)
另外,我想知道nbody程序为何采用(2)这种函数形式而非(3),主要是为了代码可读性还是性能考量?
内容的提问来源于stack exchange,提问作者tbzy
相关产品推荐
相关产品推荐

