Outcome: model a small domain with a record and collection, then select if, match, and for by the question each one answers.
Prerequisite: complete Values and Functions and understand bindings, annotations, parameters, and function results.
Give each task a shape
Create data-control.tpz:
record StudyTask {
title: string,
minutes: int,
done: bool = false,
}
function pace(task: StudyTask) -> string {
if task.done {
return "done"
}
match task.minutes {
case 1..15 => "quick"
case 16..30 => "focused"
case _ => "deep"
}
}
let tasks: Array<StudyTask> = [
StudyTask { title: "Run first program", minutes: 10, done: true },
StudyTask { title: "Build application", minutes: 25 },
]
let mut remaining = 0
for task in tasks {
if !task.done {
remaining = remaining + task.minutes
}
print("{task.title}: {pace(task)}")
}
print("remaining: {remaining} minutes")Run the same two-step loop:
topaz check data-control.tpz
topaz run data-control.tpz
It prints:
Run first program: done
Build application: focused
remaining: 25 minutesFollow the three decisions
StudyTask is a nominal record: its name and fields describe one kind of domain value. done defaults to false, so the second constructor can omit it. Array<StudyTask> says that tasks is an ordered collection of those records.
for visits each task in order, which is why the output follows the array. Inside the loop, if !task.done answers one yes/no question and updates remaining only for unfinished work.
pace asks a different question. Its first if returns early for a completed task. The following match classifies the remaining minutes into ranges, and each arm produces the function’s string result.
Decision: Array, Map, or Set?
Use Array when order and repeated values are meaningful, as they are in this study plan. Use Map when the main operation is lookup by key. Use Set when uniqueness matters more than position. Choose the collection from the observable behavior you need, not from how many items happen to exist today.
Try this
Add StudyTask { title: "Review output", minutes: 5, done: true } as the third array element. What new line appears, and does remaining change?
Answer
The new line is Review output: done. remaining stays at 25 minutes because the added task is already complete and the if body does not run for it.
Ready to continue when
You can explain why StudyTask is a record, why the collection is an Array, why iteration uses for, why accumulation uses if, and why classification uses match.
See Patterns & Control Flow, Records & Nominal Data, and Collections & Comprehensions for the standalone rules. Continue to Failures and Resources.