Course of Raku / Advanced / Control flow / Statement prefixes 🆕 / Exercises / Force eager evaluation
Solution: Force eager evaluation
Here is a possible solution to the task.
Code
say (1 .. Inf).is-lazy;
say (eager 1..3).is-lazy;
say (lazy 1..3).is-lazy;🦋 You can find the source code in the file force-eager.raku.
Output
True
False
TrueComments
A range up to
Infcannot be computed all at once, so it is lazy:.is-lazyreportsTrue.The
eagerprefix forces a list to be produced immediately, so the result is no longer lazy —.is-lazyreportsFalse. This is the direct counterpart of marking a listlazy.Do not apply
eagerto an unbounded range:eager 1 .. Inftries to compute every element at once, so the program simply hangs, consuming more and more memory until it is killed.eageris only safe on lists you know are finite.The reverse also works:
lazy 1..3marks even a short, finite range as lazy, so.is-lazyreportsTrue. The prefix sets the laziness flag regardless of how small the list is — it does not have to be infinite to be lazy.