Part I — Foundations · Chapter 5 · Lesson 3 of 5 · 10 min read
Lesson 3: Traversal, Transformation, Filtering, and Aggregation
Lesson level: Foundation
Purpose: Process collections systematically by visiting each value, deriving new values, selecting relevant items, and combining results safely.
Learning objectives
By the end of this lesson, you should be able to:
- traverse lists, strings, and map keys;
- choose between direct iteration and index-based traversal;
- transform a collection into new values;
- filter items with an explicit predicate;
- aggregate values with counters, sums, minima, and maxima;
- combine transformation, filtering, and aggregation into pipelines;
- preserve source collections when a transformation should be non-destructive;
- handle empty and invalid inputs deliberately; and
- state and test collection-processing invariants.
1. Traversal visits collection values
Traversal processes each item in a collection according to a defined order. Lists and strings are traversed in sequence order. Maps are traversed through their keys, and the current key is used to access its value.
A traversal should state what is visited, in what order, and what state changes after each item.
2. Direct list traversal
Use direct iteration when only the item value is needed:
let scores = [8, 9, 10] for score in scores { print "Score: {score}" }
The loop variable receives each list value in sequence order. The source list is not changed merely by reading each item.
3. Index-based traversal
Use a range and index when position matters:
let scores = [8, 9, 10] for index in range(0, 3) { print "Index {index}: {scores[index]}" }
The stop value is exclusive. In reusable code, derive the upper bound from the collection through supported operations instead of duplicating a literal size.
4. String traversal
Iterating a string visits its characters in sequence:
let code = "PEA" for character in code { print character }
Use string traversal for character-level analysis. Use standard string operations for higher-level tasks such as case conversion, splitting, or pattern matching when they express intent more clearly.
5. Map traversal
Iterating a map yields keys. Use each key to retrieve the corresponding value:
let metrics = {"impact": 6, "users": 25} for key in metrics { print "{key}: {metrics[key]}" }
Do not assume a business-significant order unless the contract explicitly guarantees one. When presentation order matters, define an ordered list of keys.
6. Transformation derives new values
A transformation applies a rule to each input item and produces a corresponding output. A clear transformation returns a new collection and leaves the source unchanged unless in-place behavior is explicitly required.
Example — Apply tax to prices
function add_tax(amount, rate) { return amount + (amount * rate) } let prices = [100, 250, 80] let taxed_prices = [] for price in prices { taxed_prices = taxed_prices + [add_tax(price, 0.18)] }
The result list has one output for every input and preserves sequence order.
7. Transformation invariants
Useful invariants include:
- the output count equals the number of processed input items;
- output position corresponds to input position;
- the source collection remains unchanged;
- each output satisfies the transformation's postconditions; and
- invalid input handling is consistent.
8. Transforming records
For a list of maps, build new record maps when nested independence matters:
let normalized = [] for item in inventory { let revised = { "sku": item["sku"], "quantity": item["quantity"], "active": item["quantity"] > 0 } normalized = normalized + [revised] }
This explicitly defines the output contract and avoids unexpected source mutation.
9. Higher-order transformation
A reusable transformer can accept a function value:
function transform(values, rule) { let result = [] for value in values { result = result + [rule(value)] } return result }
The contract must specify the expected callable arity and output meaning. An invalid or null item policy must also be explicit.
10. Filtering selects matching items
A filter evaluates a predicate for each item and includes the item only when the predicate is true. The output preserves the relative order of selected list items.
Example — Select high scores
let scores = [45, 82, 67, 91] let high_scores = [] for score in scores { if score >= 80 { high_scores = high_scores + [score] } }
The result is [82, 91]. The source remains unchanged.
11. Predicates should return booleans
A predicate answers one question about one item:
function is_active_item(item) { return item["active"] == true }
Validate required record keys before invoking a predicate that assumes them. Avoid relying on unrelated truthiness when an explicit domain comparison is clearer.
12. Filtering records
A list of inventory maps can be filtered by quantity and activity:
let available = [] for item in inventory { if item["active"] and item["quantity"] > 0 { available = available + [item] } }
If the result will later be mutated independently, copy or rebuild selected records rather than preserving shared nested references unintentionally.
13. Filter invariants
- Every output item came from the input.
- Every output item satisfies the predicate.
- No qualifying input item is omitted.
- Relative order is preserved.
- Output count is never greater than input count.
- The source remains unchanged for a non-destructive filter.
14. Empty filter results
An empty result is often a valid outcome meaning that no items matched. It is not automatically an error or null. The contract should distinguish “no matches” from “invalid input.”
15. Aggregation combines many items
An aggregation reduces a collection to a summary such as a count, sum, minimum, maximum, average, or grouped result. The accumulator state must have a clear meaning after every iteration.
16. Count and sum
let values = [10, 20, 30] let count = 0 let total = 0 for value in values { count += 1 total += value }
After processing k items, count equals k and total equals the sum of those k items. That relationship is the aggregation invariant.
17. Average
An average requires both a sum and a count. An empty collection has no ordinary average, so guard the zero-count case.
let average = null if count > 0 { average = total / count }
The contract should document whether an empty average returns null, a Result value later, or another explicit outcome.
18. Minimum and maximum
For a nonempty collection, initialize minimum and maximum from the first validated item rather than inventing an arbitrary sentinel.
let minimum = values[0] let maximum = values[0] for value in values { if value < minimum { minimum = value } if value > maximum { maximum = value } }
Check that the list is nonempty before reading index 0.
19. Conditional aggregation
Filtering and aggregation can be combined without building an intermediate collection:
let active_quantity = 0 for item in inventory { if item["active"] { active_quantity += item["quantity"] } }
This is efficient and clear when only the summary is needed. Build the filtered collection separately when it is also an output.
20. Grouped aggregation with maps
A map can hold one accumulator per category:
let counts = {"low": 0, "medium": 0, "high": 0} for case in cases { let priority = case["priority"] counts[priority] += 1 }
Validate the category before using it as a key. Unknown categories should produce a deliberate invalid result rather than an accidental missing-key failure.
21. A collection-processing pipeline
A robust pipeline separates stages:
- validate the collection shape;
- traverse items;
- reject or classify invalid items;
- filter relevant items;
- transform them into the required output shape;
- aggregate summaries; and
- return one complete result.
Separate stages make assumptions and failure handling visible.
22. Worked example: inventory analysis
function inventory_summary(items) { let active_items = [] let total_quantity = 0 let total_value = 0 for item in items { if item["quantity"] < 0 or item["unit_price"] < 0 { return null } if item["active"] and item["quantity"] > 0 { let value = item["quantity"] * item["unit_price"] active_items = active_items + [{ "sku": item["sku"], "quantity": item["quantity"], "value": value }] total_quantity += item["quantity"] total_value += value } } return { "items": active_items, "active_count": len(active_items), "total_quantity": total_quantity, "total_value": total_value } }
The example validates, filters, transforms, and aggregates while preserving source items.
23. Empty-input behavior
For an empty valid collection:
- a transformation returns an empty collection;
- a filter returns an empty collection;
- a count returns zero;
- a sum commonly returns its additive identity, zero;
- minimum and maximum require an explicit absent result; and
- average requires a zero-count guard.
Document these outcomes instead of allowing each caller to guess.
24. Invalid-item strategies
Choose one policy deliberately:
- fail fast on the first invalid item;
- skip invalid items and count them;
- collect validation errors for later reporting; or
- separate valid and invalid outputs.
The choice affects accounting invariants. If items are skipped, inspected must equal valid plus invalid.
25. Mutation during traversal
Changing the collection being traversed can skip items, duplicate work, or invalidate positions. Prefer producing a new collection. If in-place updates are required, keep the collection size stable and document the traversal semantics.
Never append to the same list solely to drive an unbounded traversal without a separate limit.
26. Complexity and bounds
A single traversal is linear in the number of items. Nested traversal can multiply work. Repeatedly scanning the same collection for related summaries may be clearer as one pass with several accumulators.
Resource governance still matters: validate collection sizes and output growth when data may be untrusted or externally supplied.
Common mistakes
- Using index traversal when position is irrelevant. It adds boundary risk.
- Hard-coding collection length. The loop bound drifts when data changes.
- Assuming map order expresses policy. Define an ordered key list when needed.
- Mutating source records during a transformation. Callers observe unexpected changes.
- Filtering with truthiness instead of a domain predicate. Valid zero or empty values may be lost.
- Returning null for no matches. An empty valid result differs from invalid input.
- Dividing by zero when averaging an empty collection. Guard the count.
- Initializing minimum or maximum with an arbitrary sentinel. Use the first validated item.
- Using unknown categories as map keys. Validate before aggregation.
- Changing collection size during traversal. Iteration behavior becomes fragile.
- Building unbounded output from untrusted input. Apply collection and output limits.
Guided practice
- Choose direct or index traversal for four scenarios.
- Transform [1, 2, 3] into squared values.
- Filter a score list to values at least 80.
- Count nonempty strings without building an intermediate list.
- Calculate sum and average with an empty-input guard.
- Find minimum and maximum in a nonempty list.
- Group case records by approved priority.
- State an invariant for a filter output.
- State an accounting invariant when invalid items are skipped.
- Refactor three repeated traversals into one pass with multiple accumulators.
Hands-on lab: Build a collection analysis pipeline
Scenario. Analyze a list of inventory item maps and return validated, filtered, transformed, and aggregated results.
Requirements
- Validate every required item key before access.
- Classify each item as valid or invalid.
- Count inspected, valid, and invalid items.
- Filter valid items that are active and have positive quantity.
- Transform selected items into summary maps containing sku, quantity, unit price, and inventory value.
- Aggregate selected-item count, total quantity, total value, minimum item value, maximum item value, and average item value.
- Group selected items by a documented category field.
- Return one complete result map.
- Preserve the source inventory.
- Handle an empty inventory and an empty selected result explicitly.
Required invariants
- inspected = valid + invalid;
- selected count never exceeds valid count;
- total quantity equals the sum of selected quantities;
- total value equals the sum of transformed item values;
- every transformed item corresponds to one selected source item;
- group counts sum to selected count; and
- the source inventory remains equal to its pre-run copy.
Test variants
- ordinary mixed inventory;
- empty inventory;
- all invalid items;
- valid items but no selections;
- one selected item;
- duplicate categories;
- missing keys and null fields;
- negative quantity or price;
- unknown group category; and
- large input subject to a documented maximum.
Deliverable. Submit source, pipeline diagram, contracts, prediction table, output, invariant evidence, and a source-preservation comparison.
Review questions
- What order is used when traversing a list or string?
- What does iterating a map yield?
- When is direct traversal preferable to index traversal?
- What invariants should a transformation preserve?
- What does a filter predicate return?
- Why is an empty filter result not automatically an error?
- Which accumulator states are needed for an average?
- How should minimum and maximum be initialized?
- When can filtering and aggregation be combined in one pass?
- Why must grouped categories be validated before map access?
- What accounting invariant applies when invalid items are skipped?
- Why is mutating collection size during traversal risky?
Applied challenge: Support-case analytics pipeline
Build a pipeline over a list of support-case maps. Validate each record, separate invalid records, filter open cases, transform valid open cases into operational summaries, group them by priority, and aggregate counts, affected users, and average impact.
Return a map containing selected records, invalid reason codes, group summaries, totals, minima, maxima, averages, and accounting fields. Preserve the source collection and enforce a maximum input size.
Success criteria
- Traversal order and bounds are explicit.
- Required keys are validated before access.
- Predicates return booleans.
- Transformations produce independent output records.
- Empty valid outcomes are distinct from invalid input.
- Aggregations handle zero-count cases.
- Group totals reconcile with selected records.
- All accounting and source-preservation invariants pass.
Lesson summary
Traversal visits collection values in a defined order. Transformation derives new values, filtering selects items with explicit predicates, and aggregation combines many items into summaries. Reliable collection pipelines validate shape before processing, preserve source data unless mutation is intentional, define empty-input behavior, use meaningful accumulators, validate grouping keys, reconcile accounting totals, and apply bounds to untrusted input and output growth.
Next lesson: Portable-Value Boundaries Between PeaLang and Hosts
Lesson status: Ready for review.