Is it possible to use templates to implement something like the `@show` macro from the Julia programming langauge in D?

Salih Dincer salihdb at hotmail.com
Mon Sep 9 19:29:01 UTC 2024


On Monday, 9 September 2024 at 17:56:04 UTC, monkyyy wrote:
> auto parse(char[] s)=>s[9..$-2];
> void show(T,string file= __FILE__,int line=__LINE__)(T t){
>     writeln(File(file).byLine.drop(line-1).front.parse," == 
> ",t);
> }
> void main(){
>     int i=3;
>     show(i++ + ++i * i);
>     show(i);
> }

This solution is really successful. I didn't think there could be 
any other solution than mixin(); this is utterly ingenious!

There is a working version of the code below and different tests. 
My only concern is why i == 5 in the line below when i == 28?

```d
import std;

auto parse(char[] s) => s[9..$ - 2];
void show(string file = __FILE__, int line = __LINE__, T)(T t)
{
   File(file).byLine
             .drop(line-1)
             .front
             .parse
             .writeln(" == ", t);
}

template f(ulong n) {
   static if(n < 2) const f = 1;
   else const f = n * f!(n - 1);
}

void main()
{
     int i = 3;
     show(i++ + ++i * i);
     show(i);
	T factorial(T)(T n)=>n<2?1:n*factorial(--n);
     show(factorial(10));
     show(f!10);
}
/* Prints:
i++ + ++i * i == 28
i == 5
factorial(10) == 3628800
f!10 == 3628800
*/
```
SDB at 79


More information about the Digitalmars-d-learn mailing list