Lazy eval
Tom S
h3r3tic at remove.mat.uni.torun.pl
Mon Aug 21 14:59:30 PDT 2006
While I partly agree with you, Frank, I don't want to dismiss this new
feature too soon. So let me disagree a bit ;)
Frank Benoit wrote:
> There is no possibility to choose between
>
> func( char[] a ) vs. func( char[] delegate() dg )
>
> func( funcRetInt() ); vs. func( &funcRetInt );
That is a serious problem as it breaks existing code. But if these
functions were written with lazy evaluation in mind, there would be no
sense in having such two overloads. The coder would ensure that the
expression is evaluated just once.
In order to overcome the problem with code having both func(Type) and
func(Type delegate()) overloads, but not really meaning them to be used
with lazy expression evaluation, the coder would have to make it
straight that lazy evaluation is preferred in the remaining cases.
One possible method to accomplish it is by adding a new storage
specifier, 'lazy' to the bunch of 'in', 'inout' and 'out'.
The consequences of such an approach would be:
----
void foo(lazy int x) {
static assert(is(typeof(x) : int delegate()));
writefln(x());
}
void foo(int x) {
writefln(x);
}
---
Error: foo(lazy int) conflicts with foo(int)
----
void foo(lazy int x) {
static assert(is(typeof(x) : int delegate()));
writefln(x());
}
void bar(int delegate() x) {
foo(x);
}
void bar(int x) {
writefln(x);
}
foo({return 5;}); // foo(lazy int) called
foo(5 + 5); // foo(lazy int) called, expression evaluated lazily
bar(5); // bar(int) called
foo(5 + 5); // bar(int) called, expression evaluated at call-time
bar({return 5;}); // bar(int delegate()) called
----
Which really means that lazy args and delegates could be converted
between each other without explicit casts, but in order to make a
function accept lazily-evaluated expressions, the programmer would have
to declare his/her intent clearly.
> The code isn't that much readable as it was before. You don't know what
> will happen. Will that expression be evaluated or not? Or will it be
> evaluated more than once?
Just as Walter stated, that's the same case as with 'in' vs 'inout' vs
'out' arguments. You don't know what will happen in either case
--
Tomasz Stachowiak
More information about the Digitalmars-d
mailing list