How can you read and understand the source of *naryFun in functional.d?

Tomek Sowiński just at ask.me
Sat Jan 29 10:00:49 PST 2011


Tom napisał:

> I am learning D for some time. I come from background of C, C# and Python.
> When I saw the ways to use std.algorithem's functions, I have noticed that the
> input lambda's can be writen as strings. Somewhat like the pythonic "exec". I
> went to the source of this feature in functional.d
> ("https://github.com/D-Programming-Language/phobos/blob/master/std/functional.d").
> The functions unaryFun and binaryFun. Is there a way I can read them and
> understand them easily? or maybe I missed something?

The standard library implementation must cater for a lot of corner-cases. But the essence is this:

template binaryFun(string expr) {
	auto binaryFun(T, U)(T a, U b) {
		return mixin(expr);
	}
}

unittest {
    assert (binaryFun!"a+b"(1,2) == 3);
    assert (binaryFun!"a-b"(1,2) == -1);
}

The magic happens at the mixin line. It takes any expression or statement in string form and compiles it in context of the function. Unlike pythonic exec, the string must be known at compile-time.

-- 
Tomek



More information about the Digitalmars-d-learn mailing list