PeaBox Lab › PeaLang › Learn › Chapter 8 › Lesson 2

Part II — Intermediate Development · Chapter 8 · Lesson 2 of 6 · 13 min read

Lesson 2: Collections, Strings, Mathematics, and Date-Time Operations

Lesson level: Intermediate

Purpose. Use stable standard-library operations to transform collections and text, perform dependable numerical work, and handle dates and times without hiding ordering, precision, locale, or time-zone assumptions.

Learning objectives

By the end of this lesson, you will be able to:

2.1 A common operating model

Collections, strings, numbers, and date-time values are ordinary application data, but library operations can introduce hidden assumptions. Before calling a function, confirm its input contract, return shape, mutation behavior, ordering guarantee, failure behavior, and stability level for the installed release.

A dependable workflow has four stages: validate the boundary, normalize the representation, transform with explicit operations, and verify the result against stable invariants.

Release note. The examples in this lesson show design patterns. Confirm exact module and member names with the standard-library manifest and documentation from the PeaLang release you execute.

2.2 Collections as transformation pipelines

A collection pipeline should make three things obvious: which elements enter, how each element changes, and how results are combined. Prefer small stages over one dense expression when a reader must reason about filtering, mapping, grouping, or reduction.

Conceptual pipeline:

validated = filter(records, is_valid) normalized = map(validated, normalize_record) ordered = sort(normalized, by_identifier) summary = reduce(ordered, empty_summary, add_record)

Each stage has a separate invariant. Every item in validated satisfies the predicate; every item in normalized has a canonical shape; ordered follows an explicit key; and summary is derived from exactly those ordered items.

2.3 Lists: traversal, selection, and transformation

Use list operations according to intent:

IntentTypical operationContract to verify
Visit every itemiterationTraversal order and mutation rules
Keep matching itemsfilterPredicate truth and preserved order
Transform every itemmapOutput type and cardinality
Combine itemsreduce or aggregateIdentity value and empty-input behavior
Order itemssortKey, direction, stability, and mutation
Find one itemsearchNot-found representation and duplicate policy

Do not assume a function mutates its input or returns a new list. Verify the contract and choose the form that makes ownership clear. When preserving the original matters, make the copy explicit and test that the input remains unchanged.

2.4 Maps: keys, defaults, and canonical shape

String-keyed maps are useful portable records. Safe code distinguishes a missing key from a key whose value is null, validates required keys before use, and supplies defaults only when the domain defines a legitimate default.

Normalize maps at the boundary: reject unknown critical fields when appropriate, convert accepted aliases to canonical names, validate value types and ranges, and produce a predictable map shape for the core logic.

Never depend on map iteration order unless the public contract guarantees it. When output order matters, extract entries and sort them by an explicit key before formatting or comparison.

2.5 Empty collections and aggregation identities

Empty input is a normal boundary case, not an exceptional surprise. Count and sum can have natural identities, while minimum, maximum, average, and first-item operations may require Option, Result, a documented default, or an explicit validation failure.

An aggregation identity must be neutral: zero for addition, one for multiplication, an empty list for concatenation, or an empty map for a merge strategy that defines collisions. A convenient but incorrect initial value silently corrupts every result.

2.6 Strings are data, not decoration

String operations often sit at boundaries: user input, identifiers, protocols, files, and reports. Define whether a string is free text, a code, a label, a path fragment, or a serialized value before transforming it. The correct normalization for one role can damage another.

2.7 Normalization and comparison

A common text pipeline trims permitted surrounding whitespace, applies a documented case policy, validates length and character constraints, and then compares canonical values. Preserve the original text separately when it must be displayed or audited.

Case conversion is not a substitute for a locale or identity policy. For security-sensitive identifiers, use the platform’s documented canonicalization rules rather than inventing them from lowercase conversion alone.

Illustrative pattern:

display_name = raw_name comparison_name = normalize_name(raw_name) if comparison_name == expected_name { // Use the canonical value for comparison and the original for display. }

2.8 Search, replace, split, and join

Splitting a delimited value is not equivalent to parsing CSV, JSON, a URL, or a path. Use the corresponding parser when quoting, escaping, nesting, or platform rules matter.

2.9 Unicode, length, and slicing

Human-visible characters may not correspond one-to-one with storage units. Before using length or slicing for validation or display, verify what the library counts and whether indexes can split a user-perceived character. Prefer documented Unicode-aware operations for user text.

Byte limits and character limits serve different purposes. Apply byte limits at transport or storage boundaries and user-visible length rules at the text boundary, recording which measure each constraint uses.

2.10 Safe string output

Escaping is context-specific. Text intended for a log, JSON document, CSV field, regular expression, URL, shell, or HTML context requires the matching encoder or parser. Never assume one generic replace operation safely escapes every destination.

Keep secrets, credentials, and unnecessary personal data out of transformed output. Redact before joining or formatting so sensitive fragments cannot leak through later operations.

2.11 Mathematical functions and domains

Every mathematical operation has a domain. Validate inputs before square roots, logarithms, division, powers, or trigonometric operations. Decide whether an out-of-domain value is a programmer defect, invalid external input, an expected Result, or a missing Option.

Use named intermediate values and include units in names or adjacent documentation. Mixing degrees and radians, percentages and proportions, or seconds and milliseconds can produce plausible but incorrect results.

2.12 Precision, rounding, and tolerances

Floating-point values approximate many decimal quantities. Do not use exact equality for results derived through several floating-point operations unless exact representation is guaranteed. Compare against a documented absolute or relative tolerance appropriate to the domain.

Rounding is a business rule. Specify when rounding occurs, the number of digits, and the tie-breaking policy. Round for presentation at the final boundary unless the domain requires intermediate rounding. Never use formatted display text as the value for later calculation.

NeedSafer approach
Compare measured valuesUse a documented tolerance.
Display a resultFormat at the output boundary.
Represent moneyUse the project’s approved exact or scaled-value strategy.
Reproduce simulationUse an explicit seed and record it.
Avoid invalid arithmeticValidate domains and denominators first.

2.13 Aggregates and descriptive statistics

For count, sum, minimum, maximum, mean, or related measures, define how nulls, invalid entries, empty input, and mixed numeric types are handled. The result is not meaningful unless the population and exclusions are documented.

For large or sensitive calculations, test known small cases and invariants: a count cannot be negative, minimum cannot exceed maximum, and a mean of bounded values should remain within those bounds.

2.14 Randomness and reproducibility

Random values are environmental inputs. Tests and reproducible pipelines should use an explicit seed or injected generator when the API supports it. Security tokens and cryptographic keys require cryptographic facilities, not ordinary pseudo-random helpers.

Record the seed only when doing so is safe and useful. Never log secret key material or treat a predictable generator as a security source.

2.15 Numerical failure workflow

2.16 Temporal values need a model

Distinguish a calendar date, a wall-clock time, a local date-time, an offset-bearing instant, a duration, and a time-zone identifier. They answer different questions. A birthday may be a date; a meeting may be a zoned local date-time; an audit event should identify an unambiguous instant.

Do not store all temporal concepts as informal strings. Parse at the boundary into the most precise documented representation, keep that representation through calculations, and format only for output.

2.17 Parsing and formatting

Parsing must use an explicit accepted format or a documented standard format. Reject ambiguous input such as a numeric date whose month and day order is unspecified. Formatting should similarly specify the desired pattern, locale, and time zone.

Boundary rule. Machine interchange should use a stable, unambiguous representation. Human display can be localized after the program knows the user’s locale and zone.

2.18 Instants, offsets, and time zones

An offset describes a difference from UTC at one moment; a named time zone carries historical and future transition rules. They are not interchangeable. Daylight-saving transitions can create local times that occur twice or not at all.

When converting a local time to an instant, define the zone and the policy for ambiguous or nonexistent local times. When comparing events, convert them to compatible unambiguous instants rather than comparing formatted text.

2.19 Duration versus calendar arithmetic

Adding 24 hours is duration arithmetic; adding one calendar day is calendar arithmetic. They can differ across daylight-saving changes. Likewise, adding one month requires a policy for dates that do not exist in the target month.

Choose the operation that matches the requirement: elapsed time for deadlines and telemetry, calendar movement for schedules and billing periods. Document end-of-month and leap-year behavior.

2.20 Inject the clock

Calling “now” deep inside business logic creates nondeterministic tests. Obtain the current instant at the boundary and pass it into the core function, or inject a clock abstraction. Tests can then use a fixed value.

function is_expired(expires_at, now): return now >= expires_at

This function is deterministic. The adapter that obtains now owns the environmental dependency and its capability or host contract.

2.21 Temporal edge cases

A temporal test matrix should include ordinary cases plus every edge relevant to the product’s supported zones and calendar rules.

2.22 Integrated example: deterministic activity summary

A service receives portable activity records containing an identifier, category, amount, and timestamp. It must create a daily summary without depending on input order, ambient time, or local machine settings.

Key invariants. Every accepted record belongs to exactly one category; no record outside the interval contributes; total count equals the sum of group counts; total amount equals the sum of group amounts within the chosen tolerance; and repeated runs with identical inputs produce identical output.

2.23 Common mistakes and corrections

MistakeCorrection
Assuming collection orderSort explicitly when order is part of the result.
Using a default for missing required dataValidate and return a clear failure.
Lowercasing every string indiscriminatelyApply a role-specific normalization policy.
Splitting structured data with a delimiterUse the matching parser.
Comparing floating-point results exactlyUse a documented tolerance.
Rounding during intermediate stepsRetain calculation precision unless policy says otherwise.
Parsing an ambiguous dateRequire an explicit format.
Comparing local time stringsCompare compatible temporal values or instants.
Calling now inside core logicPass an explicit clock value.
Ignoring empty inputDefine the result for every aggregate.

2.24 Diagnostic workflow

2.25 Guided practice

2.26 Hands-on lab: Build a deterministic activity analyzer

Scenario. Build a PeaLang utility that receives a portable list of synthetic activity records and produces a category summary for a supplied reporting interval. Do not use real personal data.

Record contract

Each record contains a synthetic identifier, category text, numeric amount, and an unambiguous timestamp. The caller also supplies the interval start, interval end, display zone, and an explicit report-generation time.

Required behavior

Required tests

Deliverables

Acceptance criteria

2.27 Review questions

2.28 Applied challenge

Extend the lab with a rolling seven-calendar-day comparison in the supplied display zone. Keep interval boundaries explicit, preserve deterministic ordering, calculate percentage change only when the baseline permits it, and return a typed absence or failure when it does not. Add tests around month-end, leap day, daylight-saving transitions, zero baselines, and reordered input.

Lesson summary

Standard-library mastery requires more than knowing function names. Collection pipelines need explicit order, ownership, empty-input behavior, and invariants. String workflows need role-specific normalization, Unicode awareness, contextual parsing, and safe output. Mathematical work needs domain validation, precision policy, tolerances, and controlled randomness. Date-time logic needs precise temporal types, explicit formats and zones, correct calendar or duration arithmetic, and an injected clock.

Transition to Lesson 3

The next lesson applies these principles to structured and pattern-based text processing with JSON, CSV, and regular expressions.

Lesson status: Ready for review.

← Previous Next →