Skip to content

Instantly share code, notes, and snippets.

@run-dlang
Created Dec 10, 2018
Embed
What would you like to do?
Code shared from run.dlang.io.
import std.stdio;
auto inter(Args...)(Args args)
{
import std.conv : to;
string result = "";
static foreach (argIndex, argType; Args)
{
static if (is(argType : string))
{
result ~= args[argIndex];
}
else
{
result ~= args[argIndex].to!string;
}
}
return result;
}
template somefun()
{
import std.conv : to;
static enum State
{
start = 0,
in_var = 1,
in_literal = 2,
choice = 3,
}
auto iterpolate(string s)()
{
return mixin(feach!(s, s.length, State.start));
}
string feach(string s, size_t length, State state : State.start)()
{
if (s[0] == '$')
return "inter(" ~ feach!(s[1 .. $], s.length - 1, State.in_var);
else
return "inter(\"" ~ feach!(s[0 .. $], s.length, State.in_literal);
}
string feach(string s, size_t length, State state : State.choice)()
{
if (s[0] == '$')
return "," ~ feach!(s[1 .. $], s.length - 1, State.in_var);
else
return ",\"" ~ feach!(s[0 .. $], s.length, State.in_literal);
}
string feach(string s, size_t length, State state : State.in_var)()
{
if (s[0] == ' ')
return feach!(s[0 .. $], s.length, State.choice);
else
return s[0] ~ feach!(s[1 .. $], s.length - 1, state);
}
string feach(string s, size_t length, State state : State.in_literal)()
{
if (s[0] == '$')
return "\"" ~ feach!(s[0 .. $], s.length, State.choice);
else
return s[0] ~ feach!(s[1 .. $], s.length - 1, state);
}
string feach(string s, size_t length : 0, State state : State.in_literal)()
{
return "\")";
}
string feach(string s, size_t length : 0, State state : State.in_var)()
{
return ")";
}
}
enum enableInterpolate = "mixin somefun A; alias _ = A.iterpolate;";
void main()
{
mixin(enableInterpolate);
int a = 5;
string b = "BIG B";
_!("Value of a is $a+1 and value of b is $b").writeln;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment