[challenge] Limitation in D's metaprogramming

Jonathan M Davis jmdavisProg at gmx.com
Mon Oct 18 17:43:13 PDT 2010


On Monday, October 18, 2010 17:07:16 Nick Sabalausky wrote:
> I don't know if others have noticed this before, but I think I've found a
> notable limitation in D's metaprogramming potential: There doesn't appear
> to be a way to have mutable global state at compile-time.
> 
> Challange:
> 
> Create two..."things"...they can be functions, templates, variables,
> mix-n-match, whatever. One of them increments a counter, and the other can
> be used to retreive the value. But both of these must operate at
> compile-time, and they must both be callable (directly or indirectly,
> doesn't matter) from within the context of any module that imports them.
> 
> This is an example, except it operates at run-time, not compile-time:
> 
> -----------------------------------
> // a.d
> module a;
> int value=0;
> void inc()
> {
>     value++;
> }
> int get()
> {
>     return value;
> }
> 
> void incFromA()
> {
>     inc();
> }
> 
> //b.d
> module b;
> import a;
> void incFromB()
> {
>     inc();
> }
> 
> //main.d
> import a;
> import b;
> import std.stdio;
> void main()
> {
>     inc();
>     incFromA();
>     incFromB();
>     writeln(get());
> }
> -----------------------------------
> 
> The goal of this challenge is to define a global-level manifest constant
> enum that holds a value that has been incremented from multiple modules:
> 
> enum GOAL = ????;
> 
> It can, of course, then be displayed via:
> pragma(msg, std.conv.to!string(GOAL));
> 
> At this point, I'm not concerned about order-of-execution issues resulting
> in unexpected or unpredictable values. As long as a value can be
> incremented at compile-time from multiple modules and used to initialize
> an enum manifest constant, that satisfies this challenge.

One word: monads.

Now, to get monads to work, you're going to have to be fairly organized about 
it, but that would be the classic solution to not being able to have or alter 
global state and yet still be able to effectively have global state.

- Jonathan M Davis


More information about the Digitalmars-d mailing list