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:
- Select standard-library operations for common list and map workflows.
- Build predictable transformation pipelines without unnecessary mutation.
- Normalize, search, split, join, and validate strings safely.
- Choose mathematical operations with explicit domain and precision checks.
- Represent, parse, format, compare, and shift date-time values deliberately.
- Control ordering, locale, time-zone, and clock dependencies.
- Diagnose invalid input, empty collections, numeric edge cases, and temporal ambiguity.
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:
| Intent | Typical operation | Contract to verify |
|---|---|---|
| Visit every item | iteration | Traversal order and mutation rules |
| Keep matching items | filter | Predicate truth and preserved order |
| Transform every item | map | Output type and cardinality |
| Combine items | reduce or aggregate | Identity value and empty-input behavior |
| Order items | sort | Key, direction, stability, and mutation |
| Find one item | search | Not-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
- Search: decide whether matching is exact, case-sensitive, prefix-based, substring-based, or token-based.
- Replace: state whether one occurrence or all occurrences change, and avoid rewriting structured data with blind text replacement.
- Split: define the delimiter, treatment of empty fields, maximum parts, and surrounding whitespace.
- Join: validate elements and choose a delimiter that cannot make the output ambiguous.
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.
| Need | Safer approach |
|---|---|
| Compare measured values | Use a documented tolerance. |
| Display a result | Format at the output boundary. |
| Represent money | Use the project’s approved exact or scaled-value strategy. |
| Reproduce simulation | Use an explicit seed and record it. |
| Avoid invalid arithmetic | Validate 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
- Confirm input types, units, and permitted ranges.
- Check denominators and operation domains.
- Separate intermediate calculations and inspect their values.
- Identify where rounding or conversion first occurs.
- Compare against a small independently calculated case.
- Test zero, negative, extreme, empty, and non-finite inputs when supported.
- Assert domain invariants rather than only one expected output.
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
- leap years and February 29;
- month-end arithmetic;
- midnight and date rollover;
- daylight-saving gaps and overlaps;
- offset and zone mismatches;
- inclusive versus exclusive deadlines;
- subsecond precision and truncation;
- invalid, missing, or out-of-range components.
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.
- Validate each record’s required keys, value types, numeric domain, and timestamp format.
- Normalize category text using the approved comparison policy.
- Parse timestamps into unambiguous temporal values.
- Filter records into the requested half-open interval: start inclusive, end exclusive.
- Group by canonical category.
- Compute count and sum, retaining full calculation precision.
- Sort categories by an explicit key.
- Format numbers and dates only when creating the final report.
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
| Mistake | Correction |
|---|---|
| Assuming collection order | Sort explicitly when order is part of the result. |
| Using a default for missing required data | Validate and return a clear failure. |
| Lowercasing every string indiscriminately | Apply a role-specific normalization policy. |
| Splitting structured data with a delimiter | Use the matching parser. |
| Comparing floating-point results exactly | Use a documented tolerance. |
| Rounding during intermediate steps | Retain calculation precision unless policy says otherwise. |
| Parsing an ambiguous date | Require an explicit format. |
| Comparing local time strings | Compare compatible temporal values or instants. |
| Calling now inside core logic | Pass an explicit clock value. |
| Ignoring empty input | Define the result for every aggregate. |
2.24 Diagnostic workflow
- Identify the failing domain: collection, text, numeric, or temporal.
- Verify the exact standard-library contract for the installed release.
- Inspect the input type, shape, units, encoding, and temporal representation.
- Reduce the pipeline to the first stage whose invariant fails.
- Test an ordinary case and the smallest relevant edge case.
- Check hidden environmental dependencies: order, locale, zone, clock, seed, and host capability.
- Correct the boundary or operation rather than masking the final symptom.
2.25 Guided practice
- Design a list pipeline that filters invalid scores, converts valid scores to percentages, and sorts them by identifier.
- Explain the difference between a missing map key and a key mapped to null.
- Define empty-input behavior for count, sum, minimum, maximum, and average.
- Create a normalization policy for a case-insensitive status code while preserving display text.
- Explain why splitting on commas is not a CSV parser.
- Select a tolerance for a measured-value comparison and justify it.
- Distinguish adding 24 hours from adding one calendar day.
- Rewrite a function that calls the current clock so it accepts now explicitly.
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
- Validate the outer list and every record.
- Reject missing identifiers, invalid categories, negative amounts, malformed timestamps, and an invalid interval.
- Preserve the original category for diagnostic display but derive a canonical comparison value.
- Include records from the start instant up to, but not including, the end instant.
- Group accepted records by canonical category.
- Calculate count, total, minimum, maximum, and average with documented empty-group behavior.
- Sort groups by canonical category so output does not depend on input order.
- Format report dates in the supplied display zone and format numbers only at output.
- Use the supplied generation time rather than reading the current clock.
- Return a portable summary containing accepted count, rejected count, group rows, and stable reason codes for rejected records.
Required tests
- empty input;
- one valid record;
- several records in different input orders;
- categories differing only under the approved normalization policy;
- a record exactly at the inclusive start;
- a record exactly at the exclusive end;
- negative and extreme numeric values;
- a malformed or ambiguous timestamp;
- a daylight-saving edge in a supported zone;
- a repeated run with identical inputs and fixed generation time.
Deliverables
- the analyzer source and synthetic test data;
- a boundary contract for records and report parameters;
- a table documenting normalization, precision, interval, and time-zone policies;
- expected and actual results for every required test;
- a short compatibility note listing the standard-library modules used.
Acceptance criteria
- Every accepted record contributes exactly once.
- No record at or beyond the exclusive end contributes.
- Group counts sum to the accepted count.
- Totals agree within the documented numeric strategy.
- Output order is explicit and repeatable.
- No core function reads ambient time, locale, or time zone.
- Every rejection uses a stable reason code and contains no sensitive data.
- Formatting, semantic checks, and tests pass as separate gates.
2.27 Review questions
- Which collection operation preserves cardinality, and which may reduce it?
- Why must code verify whether a sorting operation mutates its input?
- How should minimum or average behave for empty input?
- Why is map iteration order unsafe unless guaranteed?
- When should original and normalized string values both be retained?
- Why is one escaping strategy not valid for every output context?
- How do absolute and relative numeric tolerances differ in purpose?
- Why should rounding policy be explicit?
- What is the difference between an offset and a named time zone?
- Why can adding one day differ from adding 24 hours?
- How does an injected clock improve testing?
- Which invariants prove that a grouped summary did not lose or duplicate records?
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.