Assigning value to a lazy parameter in a function call
Chris Cain
clcain at uncg.edu
Fri May 11 15:27:59 PDT 2012
On Friday, 11 May 2012 at 21:39:57 UTC, Vidar Wahlberg wrote:
> 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.
The thing is, ++a != (a = a + 1). And even if it were, it's
perfectly legitimate for a lazy parameter to change the state of
things outside the scope of the function. Really, lazy is just
syntactic sugar for a delegate.
void log(lazy string message, lazy int t)
is just the same as
void log(lazy string message, int delegate() t)
the latter must be called like
log("Incrementing the meaning of life: %s", (){return ++a;});
or
log("Incrementing the meaning of life: %s", () => ++a);
while the former can appear like:
log("Incrementing the meaning of life: %s", ++a);
In this case, I'd say that the "correct" thing to do is not have
the t parameter be a lazy parameter. Generally, lazy is better
used for things like the enforce provided by std.exception ... it
looks something like this (I haven't seen it before, so this is
an approximation based on my observations):
void enforce(bool condition, lazy string msg) {
if(condition) throw new EnforceException(msg);
}
enforce(someCondition, "Well, it looks like " ~
obj.getNameFromDatabase() ~ " is in an invalid state ... here's a
helpful representation: " ~ obj.expensiveFunction());
In this case, lazy is used to prevent the expensive calls to get
the name from a database and computing a hash function unless
it's absolutely necessary. And obj's state might very well be
changed when getNameFromDatabase is called or when
expensiveFunction is run.
> (Sorry if this is a duplicate, got an error upon sending, it
> appears like the message never was sent)
It's okay. It's a known bug right now due to the mass influx of
users. It happens to all of us :)
More information about the Digitalmars-d-learn
mailing list