liveBook · Manning

IteratorSize

As explained in Julia as a Second Language

IteratorSize is a Julia iterator trait describing whether and how the number of elements in an iterator is known.

IteratorSize is a Julia collection trait that tells iteration machinery whether the number of elements is known. A collection can report HasLength when length is available, or SizeUnknown when calculating its size is ineffective or slow. section 12.5.1

The trait changes how collect builds its result. With HasLength, Julia calls length and can prepare an appropriately sized array; with SizeUnknown, it starts with an empty array and grows it as elements arrive. The default trait is HasLength, so custom collections need an explicit override when that assumption is unsuitable. section 12.5.1

A staged rocket with unknown size

For a Rocket hierarchy whose number of stages is not efficiently determined, define the trait for every Rocket subtype: import Base: iterate, IteratorSize IteratorSize(::Type{<:Rocket}) = Base.SizeUnknown() The same collection can then support operations such as map(mass, booster) and sum(thrust, booster), while collection-building code grows its output as needed. section 12.5.1 section 12.8

Listing 12.19 Add the SizeUnknown trait to the Rocket subtypes
import Base: iterate, IteratorSize

IteratorSize(::Type{<:Rocket}) = Base.SizeUnknown()

Shows the compact Julia method that assigns SizeUnknown to Rocket subtypes. section 12.5.1

How Julia as a Second Language covers it

How deep it goes
Explains traits, defaults, and collect dispatch, then demonstrates a SizeUnknown implementation for a custom collection.
Examples
Uses a staged rocket collection and demonstrates SizeUnknown alongside map, sum, and length implementations.
What it assumes
Assumes familiarity with Julia collections and iteration while introducing traits through an ability-based analogy.
What you can do after
Configure custom Julia collections with SizeUnknown when determining their element count is slow or ineffective.
How it connects
Connects IteratorSize with Julia traits, IteratorEltype, collect, iterate, and length.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Julia as a Second Language. The section links point to the parts of the book it draws on.