A const idiom + a different 'delete'

Shin Fujishiro rsinfu at gmail.com
Thu Aug 12 00:51:46 PDT 2010


bearophile <bearophileHUGS at lycos.com> wrote:
> This is an alternative way to write it that I've never used because I don't like it much:
> 
> void main() {
>     const(int[int]) aa = {
>         int[int] result;
>         foreach (i; 0 .. 10)
>             result[i] = i * i;
>         return result;
>     }();
> }

It looks like LISP's (let ...) expression and personally I like it.
The idiom is really useful for building immutable things, including
compile-time constants.

And recently I found it works well with string mixins.
--------------------
import std.conv;

auto ref reverseArgs(alias fun, Args...)(auto ref Args args)
{
    return mixin(
        {
            string rargs;
            foreach (i, Arg; Args)
            {
                if (i > 0)
                    rargs ~= ", ";
                rargs ~= "args[" ~ to!string(args.length - i - 1) ~ "]";
            }
            return "fun(" ~ rargs ~ ")";
        }());
}

void main()
{
    int div(int a, int b) { return a / b; }

    assert(reverseArgs!div(3, 27) == 9);
}


More information about the Digitalmars-d mailing list