使用方括号输出数组元素
Using square brackets for the output of array elements
此代码创建一个记录变量 (r
) 和一个包含多个数组的元组变量 (t
) 并将它们打印到标准输出:
const N = 5;
record Myrec {
var a: [1..N] int = (for i in 1..N do i);
var b: [1..N] int = (for i in 1..N do i);
var c: [1..N] int = (for i in 1..N do i);
}
proc test() {
var r: Myrec;
var t = (r.a, r.b, r.c);
writeln( "r = ", r );
writeln( "t = ", t );
}
test();
如果我运行这个代码,我得到这个输出:
r = (a = 1 2 3 4 5, b = 1 2 3 4 5, c = 1 2 3 4 5)
t = (1 2 3 4 5, 1 2 3 4 5, 1 2 3 4 5)
但我觉得输出不是很可读(特别是在 t
的情况下)。所以,我想知道是否有某种方法可以用方括号打印此类变量,例如,如下所示?
t = ([1 2 3 4 5], [1 2 3 4 5], [1 2 3 4 5])
我认为可以通过使用 writef()
+ 格式字符串 + 传递元组的每个字段(或为此目的编写一个特定的函数)来实现,但如果有一些方便的话会很好实现类似目标的方法...
根据 FormattedIO 的文档,格式字符串 %ht
(或 %jt
)似乎完成了为数组元素添加 [...]
的工作。下面附上修改后的示例代码:
record Myrec {
var n = 100;
var a = [1,2,3];
var x = 1.23;
}
proc test() {
var r: Myrec;
var t = (r.a, r.a);
writeln();
writeln( "r = ", r );
writef( "r = %ht\n", r ); // "h" -> Chapel style
writef( "r = %jt\n", r ); // "j" -> JSON style
writeln();
writeln( "t = ", t );
writef( "t = %ht\n", t );
var arr2d: [1..2, 1..3] int = (for i in 1..6 do i);
writeln();
writeln( "arr2d =\n", arr2d );
writef( "arr2d =\n%ht\n", arr2d );
}
test();
输出
r = (n = 100, a = 1 2 3, x = 1.23)
r = new Myrec(n = 100, a = [1, 2, 3], x = 1.230000e+00)
r = {"n":100, "a":[1, 2, 3], "x":1.230000e+00}
t = (1 2 3, 1 2 3)
t = ([1, 2, 3], [1, 2, 3])
arr2d =
1 2 3
4 5 6
arr2d =
[
[1, 2, 3],
[4, 5, 6]
]
此代码创建一个记录变量 (r
) 和一个包含多个数组的元组变量 (t
) 并将它们打印到标准输出:
const N = 5;
record Myrec {
var a: [1..N] int = (for i in 1..N do i);
var b: [1..N] int = (for i in 1..N do i);
var c: [1..N] int = (for i in 1..N do i);
}
proc test() {
var r: Myrec;
var t = (r.a, r.b, r.c);
writeln( "r = ", r );
writeln( "t = ", t );
}
test();
如果我运行这个代码,我得到这个输出:
r = (a = 1 2 3 4 5, b = 1 2 3 4 5, c = 1 2 3 4 5)
t = (1 2 3 4 5, 1 2 3 4 5, 1 2 3 4 5)
但我觉得输出不是很可读(特别是在 t
的情况下)。所以,我想知道是否有某种方法可以用方括号打印此类变量,例如,如下所示?
t = ([1 2 3 4 5], [1 2 3 4 5], [1 2 3 4 5])
我认为可以通过使用 writef()
+ 格式字符串 + 传递元组的每个字段(或为此目的编写一个特定的函数)来实现,但如果有一些方便的话会很好实现类似目标的方法...
根据 FormattedIO 的文档,格式字符串 %ht
(或 %jt
)似乎完成了为数组元素添加 [...]
的工作。下面附上修改后的示例代码:
record Myrec {
var n = 100;
var a = [1,2,3];
var x = 1.23;
}
proc test() {
var r: Myrec;
var t = (r.a, r.a);
writeln();
writeln( "r = ", r );
writef( "r = %ht\n", r ); // "h" -> Chapel style
writef( "r = %jt\n", r ); // "j" -> JSON style
writeln();
writeln( "t = ", t );
writef( "t = %ht\n", t );
var arr2d: [1..2, 1..3] int = (for i in 1..6 do i);
writeln();
writeln( "arr2d =\n", arr2d );
writef( "arr2d =\n%ht\n", arr2d );
}
test();
输出
r = (n = 100, a = 1 2 3, x = 1.23)
r = new Myrec(n = 100, a = [1, 2, 3], x = 1.230000e+00)
r = {"n":100, "a":[1, 2, 3], "x":1.230000e+00}
t = (1 2 3, 1 2 3)
t = ([1, 2, 3], [1, 2, 3])
arr2d =
1 2 3
4 5 6
arr2d =
[
[1, 2, 3],
[4, 5, 6]
]