Why don't lazy parameters bind to delegates? Was: Feature to get or add value to an associative array.

Jonathan M Davis newsgroup.d at jmdavisprog.com
Fri Apr 20 21:40:36 UTC 2018


On Friday, April 20, 2018 16:35:43 Steven Schveighoffer via Digitalmars-d 
wrote:
> On 4/17/18 4:49 PM, Steven Schveighoffer wrote:
> > On 4/17/18 12:18 PM, Nick Treleaven wrote:
> >> Thanks for making this pull, I've thought about solving this before. I
> >> think the function needs to provide a way to tell if the value was
> >> already present.
> >
> > Not as straightforward, but it can be done:
> >
> > bool inserted = false;
> > auto p = aa.getOrAdd("key", {inserted = true; return new Person; });
>
> Let me say I was surprised that this doesn't actually work. An in-line
> lambda will NOT work as a lazy parameter, even though that's EXACTLY
> what a lazy parameter is implemented as! And variadic lazy parameters
> are explicitly typed this way.
>
> Has that ever worked? I could have sworn it did...

I'm not sure. I mucked around with lazy like this when I was originally
working on stuff like assertThrown and assertPred 7 or 8 years ago, but I've
done _very_ little with lazy since then. My gut reaction is that it worked,
but it might not have. If you add parens after it so that you call it, it
does work, since then the result is the correct type. And if you ignore the
exact details of how lazy is implemented and consider that it's supposed to
take an expression that evaluates to a specific type, a lambda doesn't match
that unless it's called. So, it does make sense from that perspective and is
likely why it works the way it does. The compiler would basically have to
special-case delegates to accept stuff like lambdas when the type of the
lazy parameter is not a delegate. And if it _did_ special-case it, then
things might get interesting if you actually had a lazy parameter that was a
delegate. So, I don't know if it should work or not, but the workaround is
pretty simple - just add parens to call it.

- Jonathan M Davis



More information about the Digitalmars-d mailing list