liveBook · Manning

Length property

As explained in Julia as a Second Language

length is a Julia function that returns the number of elements in a collection or the size of a supported object.

In Julia, length is a function rather than a property: call length(collection) to find its number of elements. If amounts records sales for five pizza types, length(amounts) returns 5. Combined with sum(amounts), that count gives the average sold per type. section 4.3

Count versus shape

A table with 4 rows and 3 columns has length(table) == 12. Use size to ask about its dimensions instead. For a vector, do not confuse its element count with norm, which measures magnitude: norm([3, 4]) is 5.0. section 14.3

Custom iterable collections can supply their own length methods. An engine cluster knows its count directly when every engine is alike; a mixed cluster can use the length of its stored engine collection. Import Base.length before adding these methods. This lets callers ask how many engines a cluster contains and supports operations such as calculating average specific impulse. section 12.4.1

Listing 12.12 Giving Julia a way to figure out how many engines are in a cluster
import Base: length
 
length(cluster::UniformCluster) = cluster.count          #1
length(cluster::MixedCluster) = length(cluster.engines)  #1

The two methods return the same kind of answer—an engine count—from different representations of a cluster. section 12.4.1

Counting is not always cheap. For a staged rocket, a recursive length method counts one stage at a time, taking time proportional to the number of stages. Its iterable representation can instead declare IteratorSize(::Type{<:Rocket}) = Base.SizeUnknown(). That tells iteration-based operations such as map and collect not to assume an efficiently available length. section 12.5.1

How Julia as a Second Language covers it

How deep it goes
Progresses from direct array calls to custom Base.length methods and the IteratorSize alternative when counting requires traversal.
Examples
Uses pizza-sales averages, engine clusters, staged rockets, and a four-row, three-column array.
What it assumes
Starts with array operations and introduces big-O notation and iteration traits when custom collections make them relevant.
What you can do after
Build it from scratch for custom Julia collections by extending Base.length, or configure SizeUnknown when counting requires traversal.
How it connects
Connects length with sum, map, collect, iteration, IteratorSize, size, and norm.

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.