On Sunday, 27 September 2020 at 18:54:11 UTC, tastyminerals wrote:
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,

[...]

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 another way.

You can use an Algebraic [1] or SumType [2] for this:

alias Feature = SumType!(ulong, double, bool);

Feature numberOfPunctChars(string text)
{
    // ...
    return Feature(cnt);
}

Feature ratioOfDigitsToChars(string text)
{
    // ...
    return Feature(ratio);
}

Feature hasUnbalancedParens(string text)
{
    // ...
    return Feature(!isBalanced);
}

[1] http://dpldocs.info/experimental-docs/std.variant.Algebraic.html
[2] https://code.dlang.org/packages/sumtype

Reply via email to