In most programming languages, arguments passed to a function are evaluated before the function uses them, that is, they are evaluated eagerly.
To me, it seems like it would make much more sense to evaluate the arguments only once the function uses them, that is, lazily. This makes more sense to me because it seems like it would have a performance benefit: why evaluate things that are never even needed?
Moreover, suppose you wanted to implement an if
function that accepts a boolean, and an object to return if the boolean is true, and another object to return if the boolean is false:
object if(bool condition, object valueIfTrue, object valueIfFalse) {
if(condition) return valueIfTrue;
return valueIfFalse;
}
In a language that eagerly evaluates arguments, both objects are always evaluated even though the function will always only need one of them, which, at best, incurs a slight unecessary overhead, and, at worst, causes an infinite loop.
That said, since most programming languages use eager evaluation of function arguments, I assume there must be a reason why it's usually done that way. Is there some big benefit of eager evaluation here that I'm overlooking, is it just because it was easier to implement languages that way, is it just tradition, or what?
Strict evaluation (or eager evaluation) means to evaluate all the arguments to a function before evaluating the function. Applicative order evaluation is strict. But not all strict evaluation need be in applicative order. In non-strict evaluation arguments need not be evaluated until they are actually required.
Eager evaluation means expression is evaluated as soon as it is encountered where as lazy evaluation refers to evaluation of an expression when needed.
In some programming languages, eval , short for the English evaluate, is a function which evaluates a string as though it were an expression in the language, and returns a result; in others, it executes multiple lines of code as though they had been included instead of the line including the eval .
The evaluation strategy in which function arguments are evaluated before the function call is made is known as an "eager" evaluation. Eager evaluation is used by most well-known modern programming languages, and it might seem so natural that we don't even consider the possibility of alternative evaluation strategies.
There are a couple reasons I've seen for eager evaluation, both of which are important:
Lazy evaluation can be a powerful tool, but it's not without it's costs. Purely functional languages tend to avoid problem #1 because they don't have side effects (in general), but are still bitten by problem #2 at times. Languages that allow delayed evaluation (LISP macros are a form of this, though not the same as lazy evaluation) can have the best of both worlds, but at the cost of more effort on the programmer's part.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With