PeaBox Lab › PeaLang › Learn › Chapter 5 › Lesson 3

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:

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:

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

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:

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:

Document these outcomes instead of allowing each caller to guess.

24. Invalid-item strategies

Choose one policy deliberately:

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

Guided practice

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

Required invariants

Test variants

Deliverable. Submit source, pipeline diagram, contracts, prediction table, output, invariant evidence, and a source-preservation comparison.

Review questions

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

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.

← Previous Next →