如何实现支持任意参数、自动添加空格的writeln类自定义函数?
实现Chapel版自动加空格的打印函数
问题说明
Chapel里的writeln()能打印变量,但和Python的print()不一样,它不会自动在多个参数之间插空格,想输出美观格式得手动加空格:
var x = 100, y = 200; writeln(x, y); // 输出:100200 writeln("x, y =", x, y); // 输出:x, y =100200 writeln("x, y = ", x, " ", y); // 输出:x, y = 100 200(得手动补空格)
要是把参数打包成元组传进去,输出会带多余的逗号和括号,看着别扭:
writeln(("x, y =", x, y)); // 输出:(x, y =, 100, 200)
现在我能通过重载多个myprint()版本实现需求,但不想写一堆重载函数,有没有办法写一个能接收任意数量参数的函数?目前的重载示例:
proc myprint(x1) { writeln(x1); } proc myprint(x1, x2) { writeln(x1, " ", x2); } myprint("hello"); // 输出:hello myprint("hello", "world"); // 输出:hello world
解决办法:可变参数函数
Chapel支持可变参数语法,用...就能定义接收任意数量参数的函数,两种实现方式供你选:
方式一:遍历拼接
proc myprint(args...?k) { var output = ""; for i in 1..k { if i > 1 then output += " "; output += args[i]; } writeln(output); }
方式二:用字符串join方法(更简洁)
proc myprint(args...?k) { writeln(" ".join(args)); }
测试效果
var x = 100, y = 200; myprint(x, y); // 输出:100 200 myprint("x, y =", x, y); // 输出:x, y = 100 200 myprint("hello"); // 输出:hello myprint("hello", "world", "!"); // 输出:hello world !
这样一个函数就能处理所有参数数量的情况,自动在参数间加空格,和Python的print()效果一致。
内容的提问来源于stack exchange,提问作者tbzy
相关产品推荐
相关产品推荐

