How to hide a function return type in order to wrap several functions into an associated array?
tastyminerals at gmail.com
Sun Sep 27 18:54:11 UTC 2020
This is rather a generic implementation question not necessarily
related to D but I'd like to get some opinions.
I have a collection of functions that all have the same input, a
string. The output however is different and depending on what the
function does it can be ulong, double or bool. The problem is
that for each line of text I'd like to apply all these functions,
collect the results and write them into some file. For example,
auto numberOfPunctChars(string text)
const ulong cnt = text.filter!(c => c.isPunctuation).count;
return Feature!ulong("numberOfPunctChars", cnt);
auto ratioOfDigitsToChars(string text)
const double digits = numberOfDigitChars(text).val.to!double;
const double alphas = numberOfAlphaChars(text).val.to!double;
const double ratio = digits / (alphas > 0 ? alphas : digits);
return Feature!double("ratioOfDigitsToChars", ratio);
auto hasUnbalancedParens(string text)
const bool isBalanced = balancedParens(text, '(', ')') &&
balancedParens(text, '[', ']');
return Feature!bool("hasUnbalancedParens", !isBalanced);
As you can see, I created a templated Feature struct. This does
not help much because I also want to create an associative array
of ["functionName": &numberOfPunctChars]. How can I define such
an array when "Feature!T function(string)[string] allFuns"
requires defining T beforehand and using auto is not possible?
I was thinking of having a Feature struct with 3 fiels of ulong,
double and bool members but then each Feature init would look
ugly imho "Feature("name", null, 1.5, null)". There should be a
More information about the Digitalmars-d-learn