Example of Rust code
Walter Bright
newshound2 at digitalmars.com
Fri Aug 10 17:47:58 PDT 2012
On 8/10/2012 3:42 PM, bearophile wrote:
> Walter Bright:
>
>> I'd say we're doing all right.
>
> Are you serious?
You can also do things called "expression templates" in D:
import std.stdio;
auto val(T)(T v) { static struct S { T v; int eval() { return v; }} auto s =
S(v); return s; }
auto plus(A,B)(A a, B b) { static struct S { A a; B b; int eval() { return
a.eval() + b.eval(); }} auto s = S(a,b); return s; }
auto minus(A,B)(A a, B b) { static struct S { A a; B b; int eval() { return
a.eval() - b.eval(); }} auto s = S(a,b); return s; }
void main() {
auto x = minus(val(5), plus(val(3), val(1)));
writeln("val: ", x.eval());
}
relying on "parametric polymorphism". You could reduce the repetitive
boilerplate by using a template mixin, but I just banged this out in a few
minutes, and it illustrates the idea. Note that there is no heap allocation
anywhere, nor even any testing/branching.
The compiler should inline this, but doesn't, but that's not a fault in D. The
inliner could be improved.
More information about the Digitalmars-d
mailing list