I know that Java has smart/lazy evaluation in this case:
public boolean isTrue() { boolean a = false; boolean b = true; return b || (a && b); // (a && b) is not evaluated since b is true }
But what about:
public boolean isTrue() { boolean a = isATrue(); boolean b = isBTrue(); return b || a; }
Is isATrue()
called even if isBTrue()
returns true?
Streams are lazy because intermediate operations are not evaluated unless terminal operation is invoked. Each intermediate operation creates a new stream, stores the provided operation/function and return the new stream.
Lazy evaluation Represents a supplier of results. There is no requirement that a new or distinct result be returned each time the supplier is invoked. This is a functional interface whose functional method is get().
Languages that support lazy evaluation are usually functional programming languages like Haskell, which is lazy by default. Some languages, like OCaml and Scheme, let you opt into lazy behavior. Other languages like Swift and Perl 6 support it only for lists.
Lazy class loading is an important feature of the Java runtime environment as it can reduce memory usage under certain circumstances. For example, if a part of a program never is executed during a session, classes referenced only in that part of the program never will be loaded.
Well, as far as the language is concerned - yes, both functions are called.
If you rewrote the function to this:
public boolean isTrue() { return isBTrue() || isATrue(); }
then the second function will not be called, if the first is true.
But this is short-circuit evaluation, not lazy evaluation. Lazy evaluation case would look something like this:
public interface LazyBoolean { boolean eval(); } class CostlyComparison implements LazyBoolean { private int a, b; public CostlyComparison(int a, int b) { this.a=a; this.b=b; } @Override public boolean eval() { //lots of probably not-always-necessary computation here return a > b; } } public LazyBoolean isATrue() { return new CostlyComparison(10,30); //just an example } public boolean isTrue() { // so now we only pay for creation of 2 objects LazyBoolean a = isATrue(); // but the computation is not performed; LazyBoolean b = isBTrue(); // instead, it's encapsulated in a LazyBoolean return b.eval() || a.eval(); // and will be evaluated on demand; // this is the definition of lazy eval. }
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