Created
December 10, 2018 15:50
-
-
Save run-dlang/6f682fe6ca12e02acc1c6af2c67632e7 to your computer and use it in GitHub Desktop.
Code shared from run.dlang.io.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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