Inline Operator from Function.

Neia Neutuladh neia at ikeran.org
Fri Jan 25 03:52:23 UTC 2019


On Fri, 25 Jan 2019 03:45:36 +0000, Jonathan Levi wrote:
> I know this was not an intentional feature of d, but it is a cool quirk.
> 
> If you want to use a function that takes two arguments like a infix
> binary operator (similar to the back ticks in Haskell "`fun`") you can
> but a "." before and a "=" after.
> 
>      c = (a .fun= b);

Consider also:

struct Operator(alias fn) if (Parameters!fn.length == 2)
{
    Curry opBinaryRight(string op)(Parameters!fn[0] arg) if (op == "/")
    {
        return Curry(arg);
    }
    struct Curry
    {
        Parameters!fn[0] arg;
        auto opBinaryRight(string op)(Parameters!fn[1] arg2) if (op == "/")
        {
            return fn(arg, arg2);
        }
    }
}

To use it:

alias min = Operator!((a, b) => a < b ? a : b);
writeln(1 /min/ 2);

Credit to FeepingCreature for inventing this 5-10 years ago.


More information about the Digitalmars-d mailing list