how to define infix function
Meta
jared771 at gmail.com
Sun Jun 3 18:05:52 UTC 2018
On Saturday, 2 June 2018 at 23:17:48 UTC, Simen Kjærås wrote:
> On Saturday, 2 June 2018 at 22:09:49 UTC, Neia Neutuladh wrote:
>> On Saturday, 2 June 2018 at 21:44:39 UTC, greatsam4sure wrote:
>>> Sorry for the typo
>>>
>>> is it possible to define infix function in D
>>>
>>> 3.min(5)// 3: where min is a function, works in D
>>> 3 min 5 // does not work.
>>>
>>> thanks in advance
>>
>> This is a horrible abuse of D's operator overloading
>> discovered by FeepingCreature in the distant past.
>>
>> You have to delimit your custom infix operator with slashes;
>> you can't make `3 min 5` work, but you can make `3 /min/ 5`
>> work.
>>
>> Observe:
>>
>> struct Min
>> {
>> MinIntermediate!T opBinaryRight(string op, T)(T value) if
>> (op == "/")
>> {
>> return MinIntermediate!T(value);
>> }
>> }
>> struct MinIntermediate(T)
>> {
>> T value;
>> T opBinary(string op, T)(T value2) if (op == "/")
>> {
>> if (value < value2) return value;
>> return value2;
>> }
>> }
>> Min min;
>> void main()
>> {
>> writeln(1 /min/ 2);
>> }
>
> And of course, this can be generalized:
>
> struct Operator(alias fn, string operator = "/")
> {
> static auto opBinaryRight(string op : operator, T...)(T
> value1)
> {
> struct Result
> {
> auto opBinary(string op : operator, U...)(U value2)
> if (__traits(compiles, fn(value1, value2)))
> {
> return fn(value1, value2);
> }
> }
>
> Result result;
> return result;
> }
> }
>
> unittest
> {
> import std.algorithm.comparison;
>
> alias min = Operator!(std.algorithm.comparison.min);
>
> assert(1 /min/ 3 == 1);
> }
>
> Note also the use of static opBinaryRight, allowing one to
> eschew the 'min' variable.
>
> All of this said, I would suggest not using this in prod - it's
> a neat trick that shows off some of D's power, but I don't see
> a case where this would be easier to understand than a
> straightforward function call.
>
> --
> Simen
That is interesting. I don't know yet whether it's good or bad,
but certainly, it's interesting.
More information about the Digitalmars-d-learn
mailing list