How can I print a variable name and its value without typing the name twice?

mar*_*cus 6 macros d metaprogramming

When you are debugging, it's very useful to do this:

var = calc()
print("var:", var)
Run Code Online (Sandbox Code Playgroud)

Is there any language where this is easy to do? In C and C++ you can use the stringify macro operator # and in Ruby I found this question:

Ruby - 打印变量名称,然后打印其值

使用符号:var和块的解决方案就是我想要的.

在D中,我使用了这个:

void trace(alias msg)() {
    writeln(msg.stringof ~ ":" ~ to!string(msg));
}
Run Code Online (Sandbox Code Playgroud)

但我不确定这是最好的方法,因为它只适用于简单的情况.我尝试了几种方法,但有时你可以得到字符串,但不是值(因为变量超出范围),或者你必须首先混合模板然后调用函数.

那么其他语言呢?蟒蛇?F#?嘘?Shell脚本(无论哪个shell)?Perl的?(我更喜欢远离Perl,tho).TCL?Lisp,Scheme?Java的?(Java不太可能这样做).

即使在我找到某种解决方案的语言中,它也适用于简单的情况.如果我想要打印任意表达式怎么办?

如果我正在设计一种语言,这个功能将是必备的.:-)

dsi*_*cha 5

这是在D中使用编译时函数评估(CTFE)生成代码作为字符串文字的一种非常通用但稍微丑陋的方式,以及mixin用于评估它的语句:

import std.stdio, std.math;

// CTFE function that generates trace code.
string trace(string varName) {
    return "writeln(\"" ~ varName ~ ":  \", " ~ varName ~ ");";
}

void main() {
    // Trace a function call.
    mixin(trace("sqrt(5)"));

    // Trace a variable.
    int foo = 5;
    mixin(trace("foo"));
}
Run Code Online (Sandbox Code Playgroud)

唯一的问题是mixin在任何地方手动输入都是冗长的,无论你想跟踪什么都需要在丑陋的字符串文字中.

请注意,D中有两种mixin.模板mixin在很多方面都表现得更好,但是string mixins(在这个例子中使用)大致相同,因为任何代码原则上都可以通过CTFE生成混入.