The trailing closure is beautiful!

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Dec 8 16:13:09 UTC 2020


> On Tuesday, 8 December 2020 at 13:25:38 UTC, Adam D. Ruppe wrote:
> 
> > ideally too it would be slightly magic and handle flow control
> > keywords too. so `return` returns from the whole function not just
> > the delegate.  similar to D's existing opApply perhaps.
[...]

To implement this, there would need to be a standard protocol for the
delegate to signal to the parent function that it should return from the
entire call chain. E.g., the function could have been recursively
traversing some tree or graph structure, so it's not necessarily just 2
(or some other fixed number of) calls deep.  The delegate would also
ideally be able to return a value that gets propagated to the return
value of the whole function.

I thought about how this might be implemented in today's language, sans
syntactic sugar. Maybe something along these lines:

	void iterate(Args...)(void delegate(Args) cb) {
		...
		cb(args);
		...
	}

	ReturnType myFunc(...) {
		class ReturnChute : Exception {
			ReturnType value;
			this(ReturnType v) { value = v; }
		}

		try {
			iterate(..., (args) {
				//return ReturnType(1);
				throw new ReturnChute(ReturnType(1));
			});
		} catch (ReturnChute rc) {
			return rc.value;
		}
	}

Of course, the actual implementation may not necessarily use exceptions,
but this is just to express the desired semantics.  I thought about a
non-exception based solution based on a standard library type that
encapsulates the intent to return from the delegate plus the boxed
return value, but that would require a lot of boilerplate on the part of
the `iterate` function -- you'd also be at the mercy of its
implementation to actually carry out the intent to return and not simply
ignore it or do something different.  The exception based solution seems
to be the least error-prone approach.


BTW, I also vote for trailing closures in D.


T

-- 
Prosperity breeds contempt, and poverty breeds consent. -- Suck.com


More information about the Digitalmars-d mailing list