xc-basic3 icon indicating copy to clipboard operation
xc-basic3 copied to clipboard

Lazy evaluation would be welcome

Open fredrikr opened this issue 3 years ago • 4 comments

Most languages support lazy evaluation, i.e. a boolean expression is evaluated from left to right and parts that don't need to be evaluated to know the result are skipped, i.e. it's okay to write:

IF a > 0 AND b/a =2 THEN PRINT "b is 2*a";

(If "a > 0" evaluates to false, the value of the entire expression is guaranteed to be false, so "b/a = 2" is not evaulated. Similarly, the right-hand side of an OR expression can be skipped if the left-hand side evalutates to true.)

It would be nice to have this in XC=Basic.

fredrikr avatar Feb 23 '22 20:02 fredrikr

It's a nice feature but it would add a little overhead. In cases where the left-side expression is evaluated to false, the code would obviously run faster (bc the right side is skipped) but in other cases, where the entire expression is evaluated, it would be slower in total. Only the programmer could tell if it's worth. Or am I wrong?

neilsf avatar Feb 24 '22 06:02 neilsf

I don't think it would ever need to be slower than the code that is generated today. Is it possible to change code generation like this, i.e. when the result of the lefthand side is determined to be 0, short-circuit the AND operation and just say the result is 0. :

image

fredrikr avatar Feb 24 '22 09:02 fredrikr

Hmmm.... that's something the optimizer could actually do. I'll try to implement this.

neilsf avatar Feb 24 '22 12:02 neilsf

It would be nice to have, it's what is called "short circuit" and it doesn't slow down the code in any case.

AGPX avatar Jun 27 '23 21:06 AGPX