Assigning value to a lazy parameter in a function call
Jonathan M Davis
jmdavisProg at gmx.com
Fri May 11 15:14:32 PDT 2012
On Friday, May 11, 2012 23:39:44 Vidar Wahlberg wrote:
> On 2012-05-11 23:03, Chris Cain wrote:
> > On Friday, 11 May 2012 at 20:45:53 UTC, Vidar Wahlberg wrote:
> >> Perhaps the compiler should print out a warning when you're assigning
> >> a value to a lazy parameter in a function call?
> >
> > The entire point of a lazy parameter is to not be
> > calculated/processed until it's actually necessary. This is
> > normal behavior for lazy. Most actual use cases for lazy would be made
> > impractical if the compiler bombarded the programmer with warnings.
>
> I'm not suggesting that the compiler should print a warning if you're
> doing a calculation in the function call, I'm suggesting it should give
> you a warning if you're assigning the result of the calculation to a
> variable in the function call.
> In other words, «log("%s", a + 1);» would give no warning, while
> «log("%s", ++a);» and «log("%s", (a = a + 1));» would.
>
> (Sorry if this is a duplicate, got an error upon sending, it appears
> like the message never was sent)
But that's the _point_ of lazy. You make the parameter lazy because you
_don't_ want that expression executed unless it has to be. There are cases
where the lazy parameter _never_ gets evaluated. By making it lazy, you avoid
evaluating a potentially expensive expression. enforce would be a prime
example
enforce(cond, new MyException(funcWhichCreatesMsg(something)));
If cond is true, then the second argument _never_ gets evaluated. No exception
is allocated. No additional function calls are made. They _only_ happen if the
condition is false, and that exception therefore needs to be thrown.
It sounds like you want a warning for when lazy is doing the exact thing that
it was created for.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list