Skip to content

Shorthand Generators

Calibre also supports shorthand generator expressions with fn(...).

They use a very similar syntax to list comprehensions.

let evens := fn(x for x in 0..20 if x % 2 = 0);

This creates a generator without writing a full generator function body.

Shorthand generators can also include an explicit return type of type gen:<T>.

let odds := fn(x for x in 0..20 if x % 2 != 0) -> gen:<int>;

Like list comprehensions, shorthand generators can transform values and filter them with if.

let mapped := fn(x + 1 for x in 0..5);

They can also use until to stop generation early.

let inline := fn(n * 3 for n in 0..20 if n % 3 = 0 until n > 16);

Because the result is a generator, you can keep working with it lazily as an iterator.

let mapped := fn(x + 1 for x in 0..5).map(fn (x : int) -> int => x * 10).collect();
print(mapped);

Shorthand generators are useful when you want generator behavior in a small expression without defining a new function.