Operator overloading -- lets collect some use cases

Yigal Chripun yigal100 at gmail.com
Mon Dec 29 13:28:57 PST 2008


downs wrote:
>
> Scrapple.Tools uses operator overloading to provide fake infix
> keywords along the lines of [2, 3, 4] /map/ (int i) { return
> format(i); }, with a simple and convenient syntax for defining them
> (mixin(Operator!("map", "something something use lhs and rhs; "));
> ).
>
> Forcing the end user to write mixin(function()) for such keywords is
> *NOT* the way to go, for several reasons: a) it's hard to extend, and
> b) it's needlessly verbose.
>
> The reason infix keywords are useful, is because they can be used as
> a simple way to chain bijective operations together, i.e. a /foo/ b
> /map/ c /select/ d. Without infix keywords, this would take the form
> of select(map(foo(a, b), c), d), which is an atrocity because it has
> to be read in two directions - middle-leftwards for the operations,
> and middle-rightwards for the parameters.
>
> (and yes, I know it's wrong to rely on operator evaluation order. So
> sue me. )

This solution is the one taken by functional languages. ML, Scala, etc.

another solution is the one closer to OOP style where the above snippet 
becomes: a.foo(b).map(c).select(d)

D is supposed to get extension methods in the future, and this already 
works for arrays, i.e
map(T)(T[], void delegate(T) func) {...}
char[] arr;
arr.map(whatever);

this solves the problem of having to define the functions in the 
original class scope.

personally I'm not sure what's better in this case. I know I liked 
smalltalk's way of function calling:

arr inject: 0  into: whatever.

>
> Of course, a more convenient solution would be the ability to extend
> the D syntax manually, but that's unlikely to appear in our
> lifetime.

other languages solve this already. starting from Ruby that has a very 
flexible syntax that allows to define DSLs in the Ruby syntax itself in 
a natural way, going through functional languages like ML and even Lisp 
that allow to define functions as infix, and finishing with Lisp that 
had AST macros in the 60's and Nemerle which allows one to extend the 
syntax with its AST Macros (running on .net). Since D is going to get 
AST macros I'm much more optimistic than the above.



More information about the Digitalmars-d mailing list