Skip to content

Chaining

Individual operators are only half of the story. These examples check that the behaviour holds when operators are composed. They use the Tracked helper from the contract.

Streaming through a chain

where, select and first stay streaming end to end, so only as many elements are read as needed:

source = Tracked(range(100))
first_big_even = (
    flp.it(source)
        .where(lambda x: x % 2 == 0)
        .select(lambda x: x * x)
        .where(lambda x: x > 20)
        .first()
)

assert first_big_even == 36     # 6 * 6
assert source.pulled == 7       # read 0..6, nothing more

take stops reading

source = Tracked(range(100))
assert flp.it(source).select(lambda x: x + 1).take(3).to_list() == [1, 2, 3]
assert source.pulled == 3       # take(3) does not read a fourth element

Operators that must see everything

order_by has to read the whole source before it can yield its first element. It does so when the query is enumerated, not when it is built:

source = Tracked([5, 3, 9, 1, 7])
smallest_two = flp.it(source).order_by(lambda x: x).take(2)

assert source.pulled == 0       # still deferred
assert smallest_two.to_list() == [1, 3]
assert source.pulled == 5       # ordering had to see every element

Derived queries are independent

Queries built from the same source do not affect each other or the source:

original = flp.it([3, 1, 2])
ordered = original.order_by(lambda x: x)
extended = original.concat([9])

assert original.to_list() == [3, 1, 2]      # untouched by the queries derived from it
assert ordered.to_list() == [1, 2, 3]
assert extended.to_list() == [3, 1, 2, 9]
original
   │
   ├── order_by ──→ ordered
   │
   └── concat ────→ extended

ordered and extended are separate queries over original. This matches the independent-query behaviour of .NET LINQ.