Nice example for operator overload resulting in readable linear algebra expressions

Martin Tschierschke mt at smartdolphin.de
Fri Nov 19 09:53:03 UTC 2021


I just want to share a view lines of code.
The availability of operator overloading can result in very short 
and precise code for linear algebra.
To test/explore it a little I just modified the alias this 
example:
```
#!/usr/bin/env rdmd
struct Point
{
     double[2] p;
     // Forward all undefined symbols to p
     alias p this;
     auto opBinary(string op)(Point rhs)
     {
         static if (op == "+")
         {
             Point ret;
             ret[0] = p[0] + rhs.p[0];
             ret[1] = p[1] + rhs.p[1];
             return ret;
         }
         else static if (op == "-")
         {
             Point ret;
             ret[0] = p[0] - rhs.p[0];
             ret[1] = p[1] - rhs.p[1];
             return ret;
         }
         else static if (op == "*")
             return p[0] * rhs.p[0] + p[1] * rhs.p[1];
         else
             static assert(0, "Operator " ~ op ~ " not 
implemented");
     }
}

void main()
{
     import std.stdio;// : writefln,write;

     // Point behaves like a `double[2]` ...
     Point p1, p2;
     p1 = [2, 1], p2 = [1, 1];
     // ... but with extended functionality
     writef("p1*(p1 + p2) = %s*(%s + %s) =", p1, p1, p2);
     write(p1 * (p1 + p2)); // compare this to code without 
operator overload:
}
```

Compare: ``p1 * (p1 + p2)`` to something with a structure like 
``dot(p1,(add(p1,p2)).``
(With the Dlangs UFCS it might become: ``p1.dot(p1.add(p2))`` )





More information about the Digitalmars-d-learn mailing list