New programming paradigm
Biotronic via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Sep 7 07:28:14 PDT 2017
On Wednesday, 6 September 2017 at 23:20:41 UTC, EntangledQuanta
wrote:
> So, no body thinks this is a useful idea or is it that no one
> understands what I'm talking about?
Frankly, you'd written a lot of fairly dense code, so
understanding exactly what it was doing took a while. So I sat
down and rewrote it in what I'd consider more idiomatic D, partly
to better understand what it was doing, partly to facilitate
discussion of your ideas.
The usage section of your code boils down to this:
alias EnumA = TypeMap!(float, int);
alias EnumB = TypeMap!(double, byte);
auto foo(T1, T2)(T1 a, T2 b) {
import std.conv;
return T1.stringof~": "~to!string(a)~" - "~T2.stringof~":
"~to!string(b);
}
unittest {
int a = 4;
double b = 1.23;
EnumA enumAVal = EnumA.get!float;
EnumB enumBVal = EnumB.get!byte;
auto res = enumMapper!(foo, enumAVal, enumBVal)(a, b);
assert(res == "float: 4 - byte: 1");
}
With this implementation behind the scenes:
struct TypeMap(T...) {
import std.meta : staticIndexOf;
private int value;
alias value this;
alias Types = T;
static TypeMap get(T2)() if (staticIndexOf!(T2, T) > -1) {
return TypeMap(staticIndexOf!(T2, T));
}
}
template enumMapper(alias fn, Maps...) {
auto enumMapper(Args...)(Args args) {
return enumMapperImpl!(OpaqueAliasSeq!(), Args)(args);
}
auto enumMapperImpl(alias ArgTypes, Args...)(Args args) {
alias Assigned = ArgTypes.Aliases;
alias Remaining = Maps[Assigned.length..$];
static if (Remaining.length == 0) {
import std.traits : Parameters;
alias fun = fn!Assigned;
alias params = Parameters!fun;
return fun(castTuple!params(args).expand);
} else {
alias typemap = Remaining[0];
switch (typemap) {
foreach (T; typemap.Types) {
case typemap.get!T:
alias Types = OpaqueAliasSeq!(Assigned,
T);
return enumMapperImpl!Types(args);
}
default: assert(false);
}
}
}
}
template castTuple(T...) {
import std.typecons : tuple;
auto castTuple(Args...)(Args args) if (Args.length ==
T.length) {
static if (T.length == 0) {
return tuple();
} else {
auto result = .castTuple!(T[1..$])(args[1..$]);
return tuple(cast(T[0])args[0], result.expand);
}
}
}
template OpaqueAliasSeq(T...) {
alias Aliases = T;
}
More information about the Digitalmars-d-learn
mailing list