How can I dump an expression into log and execute it
Ary Borenszweig via Digitalmars-d
digitalmars-d at puremagic.com
Fri Jul 11 09:44:30 PDT 2014
On 7/11/14, 11:14 AM, H. S. Teoh via Digitalmars-d wrote:
> On Fri, Jul 11, 2014 at 08:57:26AM +0200, Jacob Carlborg via Digitalmars-d wrote:
>> On 11/07/14 03:35, Delorien wrote:
>>> Hi,
>>>
>>> I have a C macro, which takes an argument, log it and call a
>>> function. So, if I had a source code like this:
>>>
>>> {
>>> _logfx(x + 10);
>>> }
>>>
>>> the actual code would be
>>>
>>> DebugLog("x + 10");
>>> fx(x + 10);
>>>
>>> Can I make similar tricks in the D language?
>>
>> No, I don't think so. Not without passing it as a string to begin
>> with. Or AST macros, which we don't have.
> [...]
>
> Sure you can:
>
> auto logAndCall(alias func, string expr)() {
> DebugLog(expr);
> return func(mixin(expr));
> }
>
> double myFunc(double arg) { ... }
> auto result = logAndCall!(myFunc, q{1.0 + 2.0/4});
>
>
> T
>
But the OP wanted to write:
_logfx(x + 10)
Not:
logAndCall!(fx, q{x + 10})
Notice that the first one is much more readable, and also much easier to
use.
D lacks proper macros. In Crystal you can do it like this:
---
def debug_log(msg)
puts "Debug: #{msg}"
end
def fx(exp)
puts "Exp is: #{exp}"
end
macro logfx(exp)
debug_log({{exp.stringify}})
fx({{exp}})
end
logfx(1 + 2)
---
Output:
Debug: 1 + 2
Exp is: 3
I think D would be much easier to use if it had proper macros. No need
to mess around with q{...}, with string concatenations for generating
code (let the compiler do that) and also to make the code more readable
and easier to write.
Please, D designers, try looking at other languages to get some
inspiration. I read in Reddit that Walter said "I didn't have time to
look at how Rust does things". Really? As a language designer I would
try to learn about every other possible language to get the best of all
of them in my language. Looking at only C++ is not very good.
But that's just my opinion. I'd like D to be easier to use. If one day I
have to use it in my workplace, better if it's good! :-)
More information about the Digitalmars-d
mailing list