To get the program to terminate, you would need to add an upper limit on your original sequence (1...)
.
As it's written, you have an infinite sequence of numbers, starting at 1
. The following operators — the filter
, in particular — have no way of "knowing" that they can discard the rest of the sequence once they pass 3
. They have to process the entire infinite sequence, filtering out all but the first two elements, before your reduce
can produce a final result and you can print it out. (In practice, you'll eventually overflow Int, so the program would terminate then, but that's not really a good thing to rely on.)
If you don't want to change the original (1...)
, you can approximate the same behavior by swapping out your filter
with a prefix
. A filter has to look at every element; a prefix can "know" that it stops after a certain number of elements. For example, this runs very quickly and prints out 3
:
let result = (1...)
.lazy
.prefix(2)
.reduce(0) {$0 + $1}