proposal: a new string litteral to embed variables in a string

Dmitry Olshansky dmitry.olsh at gmail.com
Wed Nov 6 13:36:49 PST 2013


07-Nov-2013 01:02, Timothee Cour пишет:
> To those who don't see the use of this:
>
> which code would you rather read & write? see pastebin:
> http://dpaste.dzfl.pl/b9f65a39
>
> Another advantage is that using an autoformatter won't mess up things
> inside a r{..} literal.
>

Challenge accepted.
50 lines in current D2:

import std.algorithm, std.conv, std.array, std.uni, std.stdio;

auto embed(Vars...)(string tmpl)
{
     auto app = appender!string();
     alias Put = void delegate();
     Put[string] fns;
     foreach(i, v; Vars)
     {
         //strangely v.stringof is "v" - BUG/FEATURE ? :)
	//may do better then to!string
         fns[Vars[i].stringof] = (){ app.put(to!string(v)); };
     }

     auto slice = tmpl;
     while(!slice.empty)
     {
         auto anchor = find(slice, '@');
         app.put(slice[0..$-anchor.length]);
         if(anchor.empty)
             break;
         slice = find!(a => !isAlpha(a))(anchor[1..$]);
         auto name = anchor[1..$-slice.length];
         if(!slice.empty)
         {
             if(name in fns)
                 fns[name]();
         }
     }
     return app.data;
}

void main(){
     int a = 2;
     float b = 3.14;
     string c = "hello";
     auto x = q{var=@a, second=@b, third=@c!}.embed!(a,b,c);
     writeln(x);
     int age = 45;
     string address = "Fleet st. 15";
     dstring fieldName = "my_field";
     auto y = q{
       "firstName": "@firstName",
       "age": @age,
       "address": {
         @fieldName: "@address",
       }
     }.embed!(age, fieldName, address);
     writeln(y);
}

Prints as expected:
var=2, second=3.14, third=hello!

       "firstName": "",
       "age": 45,
       "address": {
         my_field: "Fleet st. 15",
       }


Now isn't it already nice beyond proportions?

-- 
Dmitry Olshansky


More information about the Digitalmars-d mailing list