When a learner can reproduce a familiar example but a small variation causes confusion, the problem is usually an incomplete model rather than a lack of effort. The fastest useful response is to expose the hidden state and test one boundary at a time.
Python structural pattern matching uses a match subject and ordered case patterns to test shape, constants, types and nested structure while optionally binding names. Mastery means predicting which case is attempted first, which names are captured, why a near-match fails and when an ordinary conditional is clearer. This guide begins with that mechanism, then develops it through worked traces, deliberate mistakes, explained practice and transfer decisions.
The aim is independent reasoning. A learner should be able to predict behaviour, locate the earliest wrong assumption, use a safe diagnostic procedure and defend a design choice in a new project.
Punggol families can use the guide in short sessions around homework, CCAs and rest. The activities are proposed learning exercises, not claims about a physical branch, timetable, class size, fee, school relationship or guaranteed result.
Use disposable data and repositories, preserve backups, and check version-sensitive details against the official source. Current documentation settles a technical contract; observation and explanation turn that contract into usable knowledge.
Find your next learning step
Choose the route that matches the present difficulty. Use the complete index for a systematic course.
Build the model
Chapters 1-4 . Begin here, then continue after the learner can predict, verify and explain.
Use the core tools
Chapters 5-8 . Begin here, then continue after the learner can predict, verify and explain.
Handle boundaries
Chapters 9-12 . Begin here, then continue after the learner can predict, verify and explain.
Debug and verify
Chapters 13-16 . Begin here, then continue after the learner can predict, verify and explain.
Transfer with judgment
Chapters 17-20 . Begin here, then continue after the learner can predict, verify and explain.
Open the full chapter index . Jump to capstone practice . Use the How Studying Works hub . Read the official documentation
Complete chapter index
Chapters 1-4 . Build the model
Chapters 5-8 . Use the core tools
Chapters 9-12 . Handle boundaries
Chapters 13-16 . Debug and verify
Chapters 17-20 . Transfer with judgment
A match statement evaluates its subject once, then tries case blocks from top to bottom until the first pattern and guard succeed. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is reading match as a switch on one scalar value. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Write the subject value, list the cases in order and annotate the first structural test each case performs.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
match event:
case ('done', task):
result = task
case _:
result = NoneExplained result. The first case needs a two-item sequence whose first item equals ‘done’; otherwise the wildcard fallback runs. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: homework message. Predict the rule using a command name, subject code and optional due date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A match statement evaluates its subject once, then tries case blocks from top to bottom until the first pattern and guard succeed.” Apply this procedure: Write the subject value, list the cases in order and annotate the first structural test each case performs. The expected mechanism is: The first case needs a two-item sequence whose first item equals ‘done’; otherwise the wildcard fallback runs. For the homework message, add one near-miss that exposes reading match as a switch on one scalar value. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: library record. Contrast the rule using a mapping with title, format and borrowing state. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A match statement evaluates its subject once, then tries case blocks from top to bottom until the first pattern and guard succeed.” Apply this procedure: Write the subject value, list the cases in order and annotate the first structural test each case performs. The expected mechanism is: The first case needs a two-item sequence whose first item equals ‘done’; otherwise the wildcard fallback runs. For the library record, add one near-miss that exposes reading match as a switch on one scalar value. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: CCA attendance. Stress-test the rule using tagged tuples for present, absent and late records. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A match statement evaluates its subject once, then tries case blocks from top to bottom until the first pattern and guard succeed.” Apply this procedure: Write the subject value, list the cases in order and annotate the first structural test each case performs. The expected mechanism is: The first case needs a two-item sequence whose first item equals ‘done’; otherwise the wildcard fallback runs. For the CCA attendance, add one near-miss that exposes reading match as a switch on one scalar value. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: science reading. Explain the rule using a class with quantity, unit and validity flag. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A match statement evaluates its subject once, then tries case blocks from top to bottom until the first pattern and guard succeed.” Apply this procedure: Write the subject value, list the cases in order and annotate the first structural test each case performs. The expected mechanism is: The first case needs a two-item sequence whose first item equals ‘done’; otherwise the wildcard fallback runs. For the science reading, add one near-miss that exposes reading match as a switch on one scalar value. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers reading match as a switch on one scalar value.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Write the subject value, list the cases in order and annotate the first structural test each case performs.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny revision card with a status tag and a list of evidence items. Include one ordinary case, one boundary and one deliberate failure caused by reading match as a switch on one scalar value. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: A match statement evaluates its subject once, then tries case blocks from top to bottom until the first pattern and guard succeed. It shows a trace, not only a final value. The ordinary case should demonstrate “The first case needs a two-item sequence whose first item equals ‘done’; otherwise the wildcard fallback runs.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Write the subject value, list the cases in order and annotate the first structural test each case performs. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
Literal patterns compare the subject with a stated literal, using equality semantics except for the singleton checks involving None, True and False. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is writing a bare name when a fixed constant was intended. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Use a quoted literal, a singleton or a qualified value for a fixed target; test a near-miss of the same type.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
match status:
case 'ready':
start()
case None:
wait()Explained result. The string ‘ready’ and the singleton None are tests, not new variable bindings. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: CCA attendance. Contrast the rule using tagged tuples for present, absent and late records. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Literal patterns compare the subject with a stated literal, using equality semantics except for the singleton checks involving None, True and False.” Apply this procedure: Use a quoted literal, a singleton or a qualified value for a fixed target; test a near-miss of the same type. The expected mechanism is: The string ‘ready’ and the singleton None are tests, not new variable bindings. For the CCA attendance, add one near-miss that exposes writing a bare name when a fixed constant was intended. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: science reading. Stress-test the rule using a class with quantity, unit and validity flag. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Literal patterns compare the subject with a stated literal, using equality semantics except for the singleton checks involving None, True and False.” Apply this procedure: Use a quoted literal, a singleton or a qualified value for a fixed target; test a near-miss of the same type. The expected mechanism is: The string ‘ready’ and the singleton None are tests, not new variable bindings. For the science reading, add one near-miss that exposes writing a bare name when a fixed constant was intended. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: transport update. Explain the rule using nested mappings for line, stop and delay. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Literal patterns compare the subject with a stated literal, using equality semantics except for the singleton checks involving None, True and False.” Apply this procedure: Use a quoted literal, a singleton or a qualified value for a fixed target; test a near-miss of the same type. The expected mechanism is: The string ‘ready’ and the singleton None are tests, not new variable bindings. For the transport update, add one near-miss that exposes writing a bare name when a fixed constant was intended. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: revision card. Transfer the rule using a status tag and a list of evidence items. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Literal patterns compare the subject with a stated literal, using equality semantics except for the singleton checks involving None, True and False.” Apply this procedure: Use a quoted literal, a singleton or a qualified value for a fixed target; test a near-miss of the same type. The expected mechanism is: The string ‘ready’ and the singleton None are tests, not new variable bindings. For the revision card, add one near-miss that exposes writing a bare name when a fixed constant was intended. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers writing a bare name when a fixed constant was intended.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Use a quoted literal, a singleton or a qualified value for a fixed target; test a near-miss of the same type.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny quiz response with multiple answer shapes and a confidence value. Include one ordinary case, one boundary and one deliberate failure caused by writing a bare name when a fixed constant was intended. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: Literal patterns compare the subject with a stated literal, using equality semantics except for the singleton checks involving None, True and False. It shows a trace, not only a final value. The ordinary case should demonstrate “The string ‘ready’ and the singleton None are tests, not new variable bindings.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Use a quoted literal, a singleton or a qualified value for a fixed target; test a near-miss of the same type. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
A bare unqualified name in a pattern captures the corresponding value and normally matches anything at that position. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is expecting case RED to compare with an ordinary variable named RED. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Use a literal, Enum member or other qualified value for comparison; reserve bare names for deliberate capture.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
match point:
case (0, y):
label = f'y={y}'Explained result. The pattern requires the first element to equal zero and binds the second element to y. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: transport update. Stress-test the rule using nested mappings for line, stop and delay. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A bare unqualified name in a pattern captures the corresponding value and normally matches anything at that position.” Apply this procedure: Use a literal, Enum member or other qualified value for comparison; reserve bare names for deliberate capture. The expected mechanism is: The pattern requires the first element to equal zero and binds the second element to y. For the transport update, add one near-miss that exposes expecting case RED to compare with an ordinary variable named RED. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: revision card. Explain the rule using a status tag and a list of evidence items. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A bare unqualified name in a pattern captures the corresponding value and normally matches anything at that position.” Apply this procedure: Use a literal, Enum member or other qualified value for comparison; reserve bare names for deliberate capture. The expected mechanism is: The pattern requires the first element to equal zero and binds the second element to y. For the revision card, add one near-miss that exposes expecting case RED to compare with an ordinary variable named RED. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: quiz response. Transfer the rule using multiple answer shapes and a confidence value. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A bare unqualified name in a pattern captures the corresponding value and normally matches anything at that position.” Apply this procedure: Use a literal, Enum member or other qualified value for comparison; reserve bare names for deliberate capture. The expected mechanism is: The pattern requires the first element to equal zero and binds the second element to y. For the quiz response, add one near-miss that exposes expecting case RED to compare with an ordinary variable named RED. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: file event. Predict the rule using a path action with optional metadata. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A bare unqualified name in a pattern captures the corresponding value and normally matches anything at that position.” Apply this procedure: Use a literal, Enum member or other qualified value for comparison; reserve bare names for deliberate capture. The expected mechanism is: The pattern requires the first element to equal zero and binds the second element to y. For the file event, add one near-miss that exposes expecting case RED to compare with an ordinary variable named RED. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers expecting case RED to compare with an ordinary variable named RED.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Use a literal, Enum member or other qualified value for comparison; reserve bare names for deliberate capture.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny file event with a path action with optional metadata. Include one ordinary case, one boundary and one deliberate failure caused by expecting case RED to compare with an ordinary variable named RED. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: A bare unqualified name in a pattern captures the corresponding value and normally matches anything at that position. It shows a trace, not only a final value. The ordinary case should demonstrate “The pattern requires the first element to equal zero and binds the second element to y.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Use a literal, Enum member or other qualified value for comparison; reserve bare names for deliberate capture. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
The underscore wildcard matches without binding a usable name, making it suitable for ignored positions and explicit fallbacks. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is using a named capture as a fallback and then mistaking it for a constant. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Choose underscore when the value has no later role and place a broad fallback last.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
match record:
case ('ok', value, _):
keep(value)Explained result. The third element may be anything and is deliberately not retained. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: quiz response. Explain the rule using multiple answer shapes and a confidence value. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “The underscore wildcard matches without binding a usable name, making it suitable for ignored positions and explicit fallbacks.” Apply this procedure: Choose underscore when the value has no later role and place a broad fallback last. The expected mechanism is: The third element may be anything and is deliberately not retained. For the quiz response, add one near-miss that exposes using a named capture as a fallback and then mistaking it for a constant. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: file event. Transfer the rule using a path action with optional metadata. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “The underscore wildcard matches without binding a usable name, making it suitable for ignored positions and explicit fallbacks.” Apply this procedure: Choose underscore when the value has no later role and place a broad fallback last. The expected mechanism is: The third element may be anything and is deliberately not retained. For the file event, add one near-miss that exposes using a named capture as a fallback and then mistaking it for a constant. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: homework message. Predict the rule using a command name, subject code and optional due date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “The underscore wildcard matches without binding a usable name, making it suitable for ignored positions and explicit fallbacks.” Apply this procedure: Choose underscore when the value has no later role and place a broad fallback last. The expected mechanism is: The third element may be anything and is deliberately not retained. For the homework message, add one near-miss that exposes using a named capture as a fallback and then mistaking it for a constant. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: library record. Contrast the rule using a mapping with title, format and borrowing state. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “The underscore wildcard matches without binding a usable name, making it suitable for ignored positions and explicit fallbacks.” Apply this procedure: Choose underscore when the value has no later role and place a broad fallback last. The expected mechanism is: The third element may be anything and is deliberately not retained. For the library record, add one near-miss that exposes using a named capture as a fallback and then mistaking it for a constant. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers using a named capture as a fallback and then mistaking it for a constant.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Choose underscore when the value has no later role and place a broad fallback last.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny homework message with a command name, subject code and optional due date. Include one ordinary case, one boundary and one deliberate failure caused by using a named capture as a fallback and then mistaking it for a constant. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: The underscore wildcard matches without binding a usable name, making it suitable for ignored positions and explicit fallbacks. It shows a trace, not only a final value. The ordinary case should demonstrate “The third element may be anything and is deliberately not retained.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Choose underscore when the value has no later role and place a broad fallback last. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
A sequence pattern matches supported sequence structure and element patterns, but strings and bytes are not treated as general sequence-pattern subjects. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is assuming every iterable, including a generator or string, matches a sequence pattern. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Test the documented sequence category and verify exact length before adding a star pattern.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
match command:
case ['move', x, y]:
move(int(x), int(y))Explained result. Only a three-element sequence with the literal command in position zero enters this case. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: homework message. Transfer the rule using a command name, subject code and optional due date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A sequence pattern matches supported sequence structure and element patterns, but strings and bytes are not treated as general sequence-pattern subjects.” Apply this procedure: Test the documented sequence category and verify exact length before adding a star pattern. The expected mechanism is: Only a three-element sequence with the literal command in position zero enters this case. For the homework message, add one near-miss that exposes assuming every iterable, including a generator or string, matches a sequence pattern. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: library record. Predict the rule using a mapping with title, format and borrowing state. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A sequence pattern matches supported sequence structure and element patterns, but strings and bytes are not treated as general sequence-pattern subjects.” Apply this procedure: Test the documented sequence category and verify exact length before adding a star pattern. The expected mechanism is: Only a three-element sequence with the literal command in position zero enters this case. For the library record, add one near-miss that exposes assuming every iterable, including a generator or string, matches a sequence pattern. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: CCA attendance. Contrast the rule using tagged tuples for present, absent and late records. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A sequence pattern matches supported sequence structure and element patterns, but strings and bytes are not treated as general sequence-pattern subjects.” Apply this procedure: Test the documented sequence category and verify exact length before adding a star pattern. The expected mechanism is: Only a three-element sequence with the literal command in position zero enters this case. For the CCA attendance, add one near-miss that exposes assuming every iterable, including a generator or string, matches a sequence pattern. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: science reading. Stress-test the rule using a class with quantity, unit and validity flag. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A sequence pattern matches supported sequence structure and element patterns, but strings and bytes are not treated as general sequence-pattern subjects.” Apply this procedure: Test the documented sequence category and verify exact length before adding a star pattern. The expected mechanism is: Only a three-element sequence with the literal command in position zero enters this case. For the science reading, add one near-miss that exposes assuming every iterable, including a generator or string, matches a sequence pattern. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers assuming every iterable, including a generator or string, matches a sequence pattern.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Test the documented sequence category and verify exact length before adding a star pattern.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny library record with a mapping with title, format and borrowing state. Include one ordinary case, one boundary and one deliberate failure caused by assuming every iterable, including a generator or string, matches a sequence pattern. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: A sequence pattern matches supported sequence structure and element patterns, but strings and bytes are not treated as general sequence-pattern subjects. It shows a trace, not only a final value. The ordinary case should demonstrate “Only a three-element sequence with the literal command in position zero enters this case.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Test the documented sequence category and verify exact length before adding a star pattern. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
One starred subpattern can collect zero or more middle, leading or trailing items while the remaining positions still have fixed obligations. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is assuming the star requires at least one captured item. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Test the empty collection, one item and several items, then inspect the captured list.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
match route:
case [start, *stops, end]:
plan(start, stops, end)Explained result. A two-item route is valid and binds stops to an empty list; longer routes collect the middle items. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: CCA attendance. Predict the rule using tagged tuples for present, absent and late records. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “One starred subpattern can collect zero or more middle, leading or trailing items while the remaining positions still have fixed obligations.” Apply this procedure: Test the empty collection, one item and several items, then inspect the captured list. The expected mechanism is: A two-item route is valid and binds stops to an empty list; longer routes collect the middle items. For the CCA attendance, add one near-miss that exposes assuming the star requires at least one captured item. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: science reading. Contrast the rule using a class with quantity, unit and validity flag. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “One starred subpattern can collect zero or more middle, leading or trailing items while the remaining positions still have fixed obligations.” Apply this procedure: Test the empty collection, one item and several items, then inspect the captured list. The expected mechanism is: A two-item route is valid and binds stops to an empty list; longer routes collect the middle items. For the science reading, add one near-miss that exposes assuming the star requires at least one captured item. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: transport update. Stress-test the rule using nested mappings for line, stop and delay. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “One starred subpattern can collect zero or more middle, leading or trailing items while the remaining positions still have fixed obligations.” Apply this procedure: Test the empty collection, one item and several items, then inspect the captured list. The expected mechanism is: A two-item route is valid and binds stops to an empty list; longer routes collect the middle items. For the transport update, add one near-miss that exposes assuming the star requires at least one captured item. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: revision card. Explain the rule using a status tag and a list of evidence items. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “One starred subpattern can collect zero or more middle, leading or trailing items while the remaining positions still have fixed obligations.” Apply this procedure: Test the empty collection, one item and several items, then inspect the captured list. The expected mechanism is: A two-item route is valid and binds stops to an empty list; longer routes collect the middle items. For the revision card, add one near-miss that exposes assuming the star requires at least one captured item. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers assuming the star requires at least one captured item.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Test the empty collection, one item and several items, then inspect the captured list.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny CCA attendance with tagged tuples for present, absent and late records. Include one ordinary case, one boundary and one deliberate failure caused by assuming the star requires at least one captured item. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: One starred subpattern can collect zero or more middle, leading or trailing items while the remaining positions still have fixed obligations. It shows a trace, not only a final value. The ordinary case should demonstrate “A two-item route is valid and binds stops to an empty list; longer routes collect the middle items.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Test the empty collection, one item and several items, then inspect the captured list. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
A mapping pattern asks for specified keys and applies subpatterns to their values; extra keys are normally allowed. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is treating a mapping pattern like exact dictionary equality. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. List required keys separately from permitted extras and use a rest capture only when extras matter.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
match payload:
case {'type':'quiz','score':score}:
record(score)Explained result. The required keys must exist with matching values; unrelated keys do not by themselves make the case fail. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: transport update. Contrast the rule using nested mappings for line, stop and delay. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A mapping pattern asks for specified keys and applies subpatterns to their values; extra keys are normally allowed.” Apply this procedure: List required keys separately from permitted extras and use a rest capture only when extras matter. The expected mechanism is: The required keys must exist with matching values; unrelated keys do not by themselves make the case fail. For the transport update, add one near-miss that exposes treating a mapping pattern like exact dictionary equality. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: revision card. Stress-test the rule using a status tag and a list of evidence items. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A mapping pattern asks for specified keys and applies subpatterns to their values; extra keys are normally allowed.” Apply this procedure: List required keys separately from permitted extras and use a rest capture only when extras matter. The expected mechanism is: The required keys must exist with matching values; unrelated keys do not by themselves make the case fail. For the revision card, add one near-miss that exposes treating a mapping pattern like exact dictionary equality. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: quiz response. Explain the rule using multiple answer shapes and a confidence value. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A mapping pattern asks for specified keys and applies subpatterns to their values; extra keys are normally allowed.” Apply this procedure: List required keys separately from permitted extras and use a rest capture only when extras matter. The expected mechanism is: The required keys must exist with matching values; unrelated keys do not by themselves make the case fail. For the quiz response, add one near-miss that exposes treating a mapping pattern like exact dictionary equality. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: file event. Transfer the rule using a path action with optional metadata. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A mapping pattern asks for specified keys and applies subpatterns to their values; extra keys are normally allowed.” Apply this procedure: List required keys separately from permitted extras and use a rest capture only when extras matter. The expected mechanism is: The required keys must exist with matching values; unrelated keys do not by themselves make the case fail. For the file event, add one near-miss that exposes treating a mapping pattern like exact dictionary equality. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers treating a mapping pattern like exact dictionary equality.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “List required keys separately from permitted extras and use a rest capture only when extras matter.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny science reading with a class with quantity, unit and validity flag. Include one ordinary case, one boundary and one deliberate failure caused by treating a mapping pattern like exact dictionary equality. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: A mapping pattern asks for specified keys and applies subpatterns to their values; extra keys are normally allowed. It shows a trace, not only a final value. The ordinary case should demonstrate “The required keys must exist with matching values; unrelated keys do not by themselves make the case fail.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: List required keys separately from permitted extras and use a rest capture only when extras matter. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
A double-star capture in a mapping pattern collects unmatched key-value pairs after required keys are satisfied. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is expecting missing required keys to appear in the rest mapping. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Validate required keys first, then inspect or reject extras according to project policy.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
match data:
case {'id': ident, **extra}:
save(ident, extra)Explained result. id is required and captured separately; all remaining entries become the extra dictionary. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: quiz response. Stress-test the rule using multiple answer shapes and a confidence value. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A double-star capture in a mapping pattern collects unmatched key-value pairs after required keys are satisfied.” Apply this procedure: Validate required keys first, then inspect or reject extras according to project policy. The expected mechanism is: id is required and captured separately; all remaining entries become the extra dictionary. For the quiz response, add one near-miss that exposes expecting missing required keys to appear in the rest mapping. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: file event. Explain the rule using a path action with optional metadata. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A double-star capture in a mapping pattern collects unmatched key-value pairs after required keys are satisfied.” Apply this procedure: Validate required keys first, then inspect or reject extras according to project policy. The expected mechanism is: id is required and captured separately; all remaining entries become the extra dictionary. For the file event, add one near-miss that exposes expecting missing required keys to appear in the rest mapping. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: homework message. Transfer the rule using a command name, subject code and optional due date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A double-star capture in a mapping pattern collects unmatched key-value pairs after required keys are satisfied.” Apply this procedure: Validate required keys first, then inspect or reject extras according to project policy. The expected mechanism is: id is required and captured separately; all remaining entries become the extra dictionary. For the homework message, add one near-miss that exposes expecting missing required keys to appear in the rest mapping. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: library record. Predict the rule using a mapping with title, format and borrowing state. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A double-star capture in a mapping pattern collects unmatched key-value pairs after required keys are satisfied.” Apply this procedure: Validate required keys first, then inspect or reject extras according to project policy. The expected mechanism is: id is required and captured separately; all remaining entries become the extra dictionary. For the library record, add one near-miss that exposes expecting missing required keys to appear in the rest mapping. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers expecting missing required keys to appear in the rest mapping.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Validate required keys first, then inspect or reject extras according to project policy.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny transport update with nested mappings for line, stop and delay. Include one ordinary case, one boundary and one deliberate failure caused by expecting missing required keys to appear in the rest mapping. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: A double-star capture in a mapping pattern collects unmatched key-value pairs after required keys are satisfied. It shows a trace, not only a final value. The ordinary case should demonstrate “id is required and captured separately; all remaining entries become the extra dictionary.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Validate required keys first, then inspect or reject extras according to project policy. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
A class pattern first checks the subject type and then matches named attributes or supported positional fields. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is believing the syntax calls the class constructor. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Treat the class name as a type pattern and verify the attributes exposed to matching.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
match reading:
case Reading(value=v, unit='cm'):
use(v)Explained result. The subject must be a Reading instance whose unit attribute matches ‘cm’; value is captured as v. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: homework message. Explain the rule using a command name, subject code and optional due date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A class pattern first checks the subject type and then matches named attributes or supported positional fields.” Apply this procedure: Treat the class name as a type pattern and verify the attributes exposed to matching. The expected mechanism is: The subject must be a Reading instance whose unit attribute matches ‘cm’; value is captured as v. For the homework message, add one near-miss that exposes believing the syntax calls the class constructor. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: library record. Transfer the rule using a mapping with title, format and borrowing state. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A class pattern first checks the subject type and then matches named attributes or supported positional fields.” Apply this procedure: Treat the class name as a type pattern and verify the attributes exposed to matching. The expected mechanism is: The subject must be a Reading instance whose unit attribute matches ‘cm’; value is captured as v. For the library record, add one near-miss that exposes believing the syntax calls the class constructor. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: CCA attendance. Predict the rule using tagged tuples for present, absent and late records. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A class pattern first checks the subject type and then matches named attributes or supported positional fields.” Apply this procedure: Treat the class name as a type pattern and verify the attributes exposed to matching. The expected mechanism is: The subject must be a Reading instance whose unit attribute matches ‘cm’; value is captured as v. For the CCA attendance, add one near-miss that exposes believing the syntax calls the class constructor. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: science reading. Contrast the rule using a class with quantity, unit and validity flag. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A class pattern first checks the subject type and then matches named attributes or supported positional fields.” Apply this procedure: Treat the class name as a type pattern and verify the attributes exposed to matching. The expected mechanism is: The subject must be a Reading instance whose unit attribute matches ‘cm’; value is captured as v. For the science reading, add one near-miss that exposes believing the syntax calls the class constructor. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers believing the syntax calls the class constructor.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Treat the class name as a type pattern and verify the attributes exposed to matching.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny revision card with a status tag and a list of evidence items. Include one ordinary case, one boundary and one deliberate failure caused by believing the syntax calls the class constructor. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: A class pattern first checks the subject type and then matches named attributes or supported positional fields. It shows a trace, not only a final value. The ordinary case should demonstrate “The subject must be a Reading instance whose unit attribute matches ‘cm’; value is captured as v.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Treat the class name as a type pattern and verify the attributes exposed to matching. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
CHAPTER 10 OF 20 . Handle boundaries
10. Positional class patterns and __match_args__
Positional class patterns are translated using the class __match_args__ contract, so position is an API decision rather than a visual guess. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is assuming constructor parameter order always defines positional matching. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Inspect __match_args__ and prefer keyword patterns when field meaning should remain explicit.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
class Point:
__match_args__ = ('x','y')
match p:
case Point(0, y): ...Explained result. The pattern checks x against zero and captures y because the class explicitly publishes that positional order. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: CCA attendance. Transfer the rule using tagged tuples for present, absent and late records. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Positional class patterns are translated using the class __match_args__ contract, so position is an API decision rather than a visual guess.” Apply this procedure: Inspect __match_args__ and prefer keyword patterns when field meaning should remain explicit. The expected mechanism is: The pattern checks x against zero and captures y because the class explicitly publishes that positional order. For the CCA attendance, add one near-miss that exposes assuming constructor parameter order always defines positional matching. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: science reading. Predict the rule using a class with quantity, unit and validity flag. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Positional class patterns are translated using the class __match_args__ contract, so position is an API decision rather than a visual guess.” Apply this procedure: Inspect __match_args__ and prefer keyword patterns when field meaning should remain explicit. The expected mechanism is: The pattern checks x against zero and captures y because the class explicitly publishes that positional order. For the science reading, add one near-miss that exposes assuming constructor parameter order always defines positional matching. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: transport update. Contrast the rule using nested mappings for line, stop and delay. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Positional class patterns are translated using the class __match_args__ contract, so position is an API decision rather than a visual guess.” Apply this procedure: Inspect __match_args__ and prefer keyword patterns when field meaning should remain explicit. The expected mechanism is: The pattern checks x against zero and captures y because the class explicitly publishes that positional order. For the transport update, add one near-miss that exposes assuming constructor parameter order always defines positional matching. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: revision card. Stress-test the rule using a status tag and a list of evidence items. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Positional class patterns are translated using the class __match_args__ contract, so position is an API decision rather than a visual guess.” Apply this procedure: Inspect __match_args__ and prefer keyword patterns when field meaning should remain explicit. The expected mechanism is: The pattern checks x against zero and captures y because the class explicitly publishes that positional order. For the revision card, add one near-miss that exposes assuming constructor parameter order always defines positional matching. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers assuming constructor parameter order always defines positional matching.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Inspect __match_args__ and prefer keyword patterns when field meaning should remain explicit.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny quiz response with multiple answer shapes and a confidence value. Include one ordinary case, one boundary and one deliberate failure caused by assuming constructor parameter order always defines positional matching. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: Positional class patterns are translated using the class __match_args__ contract, so position is an API decision rather than a visual guess. It shows a trace, not only a final value. The ordinary case should demonstrate “The pattern checks x against zero and captures y because the class explicitly publishes that positional order.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Inspect __match_args__ and prefer keyword patterns when field meaning should remain explicit. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
An OR pattern succeeds when any alternative succeeds, and every alternative must bind the same set of names. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is binding a name in only one alternative and expecting it to exist conditionally. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Align bindings across alternatives and test each branch plus a near-miss.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
match command:
case ('quit', code) | ('exit', code):
stop(code)Explained result. Either tag is accepted and both alternatives bind code, so the case body has one stable name contract. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: transport update. Predict the rule using nested mappings for line, stop and delay. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “An OR pattern succeeds when any alternative succeeds, and every alternative must bind the same set of names.” Apply this procedure: Align bindings across alternatives and test each branch plus a near-miss. The expected mechanism is: Either tag is accepted and both alternatives bind code, so the case body has one stable name contract. For the transport update, add one near-miss that exposes binding a name in only one alternative and expecting it to exist conditionally. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: revision card. Contrast the rule using a status tag and a list of evidence items. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “An OR pattern succeeds when any alternative succeeds, and every alternative must bind the same set of names.” Apply this procedure: Align bindings across alternatives and test each branch plus a near-miss. The expected mechanism is: Either tag is accepted and both alternatives bind code, so the case body has one stable name contract. For the revision card, add one near-miss that exposes binding a name in only one alternative and expecting it to exist conditionally. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: quiz response. Stress-test the rule using multiple answer shapes and a confidence value. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “An OR pattern succeeds when any alternative succeeds, and every alternative must bind the same set of names.” Apply this procedure: Align bindings across alternatives and test each branch plus a near-miss. The expected mechanism is: Either tag is accepted and both alternatives bind code, so the case body has one stable name contract. For the quiz response, add one near-miss that exposes binding a name in only one alternative and expecting it to exist conditionally. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: file event. Explain the rule using a path action with optional metadata. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “An OR pattern succeeds when any alternative succeeds, and every alternative must bind the same set of names.” Apply this procedure: Align bindings across alternatives and test each branch plus a near-miss. The expected mechanism is: Either tag is accepted and both alternatives bind code, so the case body has one stable name contract. For the file event, add one near-miss that exposes binding a name in only one alternative and expecting it to exist conditionally. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers binding a name in only one alternative and expecting it to exist conditionally.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Align bindings across alternatives and test each branch plus a near-miss.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny file event with a path action with optional metadata. Include one ordinary case, one boundary and one deliberate failure caused by binding a name in only one alternative and expecting it to exist conditionally. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: An OR pattern succeeds when any alternative succeeds, and every alternative must bind the same set of names. It shows a trace, not only a final value. The ordinary case should demonstrate “Either tag is accepted and both alternatives bind code, so the case body has one stable name contract.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Align bindings across alternatives and test each branch plus a near-miss. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
An AS pattern matches a subpattern and also binds the entire matched value, preserving both parts and context. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is reconstructing the whole value from captures when identity or extra fields matter. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Use a narrow subpattern followed by as name, then state why the whole subject is needed.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
match point:
case (x, y) as pair:
log(pair, x, y)Explained result. The pair must match the two-element pattern; pair receives the whole subject while x and y receive its elements. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: quiz response. Contrast the rule using multiple answer shapes and a confidence value. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “An AS pattern matches a subpattern and also binds the entire matched value, preserving both parts and context.” Apply this procedure: Use a narrow subpattern followed by as name, then state why the whole subject is needed. The expected mechanism is: The pair must match the two-element pattern; pair receives the whole subject while x and y receive its elements. For the quiz response, add one near-miss that exposes reconstructing the whole value from captures when identity or extra fields matter. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: file event. Stress-test the rule using a path action with optional metadata. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “An AS pattern matches a subpattern and also binds the entire matched value, preserving both parts and context.” Apply this procedure: Use a narrow subpattern followed by as name, then state why the whole subject is needed. The expected mechanism is: The pair must match the two-element pattern; pair receives the whole subject while x and y receive its elements. For the file event, add one near-miss that exposes reconstructing the whole value from captures when identity or extra fields matter. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: homework message. Explain the rule using a command name, subject code and optional due date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “An AS pattern matches a subpattern and also binds the entire matched value, preserving both parts and context.” Apply this procedure: Use a narrow subpattern followed by as name, then state why the whole subject is needed. The expected mechanism is: The pair must match the two-element pattern; pair receives the whole subject while x and y receive its elements. For the homework message, add one near-miss that exposes reconstructing the whole value from captures when identity or extra fields matter. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: library record. Transfer the rule using a mapping with title, format and borrowing state. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “An AS pattern matches a subpattern and also binds the entire matched value, preserving both parts and context.” Apply this procedure: Use a narrow subpattern followed by as name, then state why the whole subject is needed. The expected mechanism is: The pair must match the two-element pattern; pair receives the whole subject while x and y receive its elements. For the library record, add one near-miss that exposes reconstructing the whole value from captures when identity or extra fields matter. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers reconstructing the whole value from captures when identity or extra fields matter.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Use a narrow subpattern followed by as name, then state why the whole subject is needed.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny homework message with a command name, subject code and optional due date. Include one ordinary case, one boundary and one deliberate failure caused by reconstructing the whole value from captures when identity or extra fields matter. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: An AS pattern matches a subpattern and also binds the entire matched value, preserving both parts and context. It shows a trace, not only a final value. The ordinary case should demonstrate “The pair must match the two-element pattern; pair receives the whole subject while x and y receive its elements.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Use a narrow subpattern followed by as name, then state why the whole subject is needed. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
A guard runs only after its pattern succeeds and its captures are available; a false guard continues with later cases. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is putting side effects in a guard and forgetting that failed guards still evaluated them. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Keep guards short and pure, and separate structural eligibility from an additional boolean policy.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
match result:
case {'score': s} if s >= 75:
band = 'strong'
case {'score': s}:
band = 'developing'Explained result. Both cases require score; the guard decides which body handles scores at or above 75. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: homework message. Stress-test the rule using a command name, subject code and optional due date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A guard runs only after its pattern succeeds and its captures are available; a false guard continues with later cases.” Apply this procedure: Keep guards short and pure, and separate structural eligibility from an additional boolean policy. The expected mechanism is: Both cases require score; the guard decides which body handles scores at or above 75. For the homework message, add one near-miss that exposes putting side effects in a guard and forgetting that failed guards still evaluated them. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: library record. Explain the rule using a mapping with title, format and borrowing state. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A guard runs only after its pattern succeeds and its captures are available; a false guard continues with later cases.” Apply this procedure: Keep guards short and pure, and separate structural eligibility from an additional boolean policy. The expected mechanism is: Both cases require score; the guard decides which body handles scores at or above 75. For the library record, add one near-miss that exposes putting side effects in a guard and forgetting that failed guards still evaluated them. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: CCA attendance. Transfer the rule using tagged tuples for present, absent and late records. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A guard runs only after its pattern succeeds and its captures are available; a false guard continues with later cases.” Apply this procedure: Keep guards short and pure, and separate structural eligibility from an additional boolean policy. The expected mechanism is: Both cases require score; the guard decides which body handles scores at or above 75. For the CCA attendance, add one near-miss that exposes putting side effects in a guard and forgetting that failed guards still evaluated them. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: science reading. Predict the rule using a class with quantity, unit and validity flag. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A guard runs only after its pattern succeeds and its captures are available; a false guard continues with later cases.” Apply this procedure: Keep guards short and pure, and separate structural eligibility from an additional boolean policy. The expected mechanism is: Both cases require score; the guard decides which body handles scores at or above 75. For the science reading, add one near-miss that exposes putting side effects in a guard and forgetting that failed guards still evaluated them. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers putting side effects in a guard and forgetting that failed guards still evaluated them.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Keep guards short and pure, and separate structural eligibility from an additional boolean policy.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny library record with a mapping with title, format and borrowing state. Include one ordinary case, one boundary and one deliberate failure caused by putting side effects in a guard and forgetting that failed guards still evaluated them. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: A guard runs only after its pattern succeeds and its captures are available; a false guard continues with later cases. It shows a trace, not only a final value. The ordinary case should demonstrate “Both cases require score; the guard decides which body handles scores at or above 75.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Keep guards short and pure, and separate structural eligibility from an additional boolean policy. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
Because only the first successful case runs, specific patterns must normally precede patterns that subsume them. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is placing a capture or wildcard before narrower cases. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. For every adjacent pair, ask whether an earlier case can already accept every subject of the later one.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
match value:
case 0: label='zero'
case int(): label='integer'
case _: label='other'Explained result. Zero reaches the literal case before the broader integer type pattern; other integers reach the second case. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: CCA attendance. Explain the rule using tagged tuples for present, absent and late records. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Because only the first successful case runs, specific patterns must normally precede patterns that subsume them.” Apply this procedure: For every adjacent pair, ask whether an earlier case can already accept every subject of the later one. The expected mechanism is: Zero reaches the literal case before the broader integer type pattern; other integers reach the second case. For the CCA attendance, add one near-miss that exposes placing a capture or wildcard before narrower cases. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: science reading. Transfer the rule using a class with quantity, unit and validity flag. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Because only the first successful case runs, specific patterns must normally precede patterns that subsume them.” Apply this procedure: For every adjacent pair, ask whether an earlier case can already accept every subject of the later one. The expected mechanism is: Zero reaches the literal case before the broader integer type pattern; other integers reach the second case. For the science reading, add one near-miss that exposes placing a capture or wildcard before narrower cases. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: transport update. Predict the rule using nested mappings for line, stop and delay. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Because only the first successful case runs, specific patterns must normally precede patterns that subsume them.” Apply this procedure: For every adjacent pair, ask whether an earlier case can already accept every subject of the later one. The expected mechanism is: Zero reaches the literal case before the broader integer type pattern; other integers reach the second case. For the transport update, add one near-miss that exposes placing a capture or wildcard before narrower cases. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: revision card. Contrast the rule using a status tag and a list of evidence items. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Because only the first successful case runs, specific patterns must normally precede patterns that subsume them.” Apply this procedure: For every adjacent pair, ask whether an earlier case can already accept every subject of the later one. The expected mechanism is: Zero reaches the literal case before the broader integer type pattern; other integers reach the second case. For the revision card, add one near-miss that exposes placing a capture or wildcard before narrower cases. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers placing a capture or wildcard before narrower cases.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “For every adjacent pair, ask whether an earlier case can already accept every subject of the later one.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny CCA attendance with tagged tuples for present, absent and late records. Include one ordinary case, one boundary and one deliberate failure caused by placing a capture or wildcard before narrower cases. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: Because only the first successful case runs, specific patterns must normally precede patterns that subsume them. It shows a trace, not only a final value. The ordinary case should demonstrate “Zero reaches the literal case before the broader integer type pattern; other integers reach the second case.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: For every adjacent pair, ask whether an earlier case can already accept every subject of the later one. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
Bindings made while attempting a pattern that later fails should not be used as a portable program contract; code should rely only on names from the selected case. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is reading partially bound local names after the match statement. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Keep work inside the case body or assign one explicit result in every successful branch.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
match subject:
case [x, 0]:
result = x
case _:
result = NoneExplained result. The later program uses result, which every branch defines, rather than relying on implementation details of a failed pattern. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: transport update. Transfer the rule using nested mappings for line, stop and delay. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Bindings made while attempting a pattern that later fails should not be used as a portable program contract; code should rely only on names from the selected case.” Apply this procedure: Keep work inside the case body or assign one explicit result in every successful branch. The expected mechanism is: The later program uses result, which every branch defines, rather than relying on implementation details of a failed pattern. For the transport update, add one near-miss that exposes reading partially bound local names after the match statement. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: revision card. Predict the rule using a status tag and a list of evidence items. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Bindings made while attempting a pattern that later fails should not be used as a portable program contract; code should rely only on names from the selected case.” Apply this procedure: Keep work inside the case body or assign one explicit result in every successful branch. The expected mechanism is: The later program uses result, which every branch defines, rather than relying on implementation details of a failed pattern. For the revision card, add one near-miss that exposes reading partially bound local names after the match statement. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: quiz response. Contrast the rule using multiple answer shapes and a confidence value. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Bindings made while attempting a pattern that later fails should not be used as a portable program contract; code should rely only on names from the selected case.” Apply this procedure: Keep work inside the case body or assign one explicit result in every successful branch. The expected mechanism is: The later program uses result, which every branch defines, rather than relying on implementation details of a failed pattern. For the quiz response, add one near-miss that exposes reading partially bound local names after the match statement. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: file event. Stress-test the rule using a path action with optional metadata. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Bindings made while attempting a pattern that later fails should not be used as a portable program contract; code should rely only on names from the selected case.” Apply this procedure: Keep work inside the case body or assign one explicit result in every successful branch. The expected mechanism is: The later program uses result, which every branch defines, rather than relying on implementation details of a failed pattern. For the file event, add one near-miss that exposes reading partially bound local names after the match statement. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers reading partially bound local names after the match statement.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Keep work inside the case body or assign one explicit result in every successful branch.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny science reading with a class with quantity, unit and validity flag. Include one ordinary case, one boundary and one deliberate failure caused by reading partially bound local names after the match statement. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: Bindings made while attempting a pattern that later fails should not be used as a portable program contract; code should rely only on names from the selected case. It shows a trace, not only a final value. The ordinary case should demonstrate “The later program uses result, which every branch defines, rather than relying on implementation details of a failed pattern.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Keep work inside the case body or assign one explicit result in every successful branch. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
Several built-in classes accept a single positional subpattern that matches the whole value, enabling concise type-and-value tests. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is assuming all user classes inherit the same single-positional behaviour. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Check the documented special cases and prefer explicit named attributes for user-defined classes.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
match value:
case int(n) if n > 0:
label='positive int'Explained result. The case checks that value is an int, captures the whole integer as n and then applies the positive guard. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: quiz response. Predict the rule using multiple answer shapes and a confidence value. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Several built-in classes accept a single positional subpattern that matches the whole value, enabling concise type-and-value tests.” Apply this procedure: Check the documented special cases and prefer explicit named attributes for user-defined classes. The expected mechanism is: The case checks that value is an int, captures the whole integer as n and then applies the positive guard. For the quiz response, add one near-miss that exposes assuming all user classes inherit the same single-positional behaviour. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: file event. Contrast the rule using a path action with optional metadata. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Several built-in classes accept a single positional subpattern that matches the whole value, enabling concise type-and-value tests.” Apply this procedure: Check the documented special cases and prefer explicit named attributes for user-defined classes. The expected mechanism is: The case checks that value is an int, captures the whole integer as n and then applies the positive guard. For the file event, add one near-miss that exposes assuming all user classes inherit the same single-positional behaviour. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: homework message. Stress-test the rule using a command name, subject code and optional due date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Several built-in classes accept a single positional subpattern that matches the whole value, enabling concise type-and-value tests.” Apply this procedure: Check the documented special cases and prefer explicit named attributes for user-defined classes. The expected mechanism is: The case checks that value is an int, captures the whole integer as n and then applies the positive guard. For the homework message, add one near-miss that exposes assuming all user classes inherit the same single-positional behaviour. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: library record. Explain the rule using a mapping with title, format and borrowing state. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Several built-in classes accept a single positional subpattern that matches the whole value, enabling concise type-and-value tests.” Apply this procedure: Check the documented special cases and prefer explicit named attributes for user-defined classes. The expected mechanism is: The case checks that value is an int, captures the whole integer as n and then applies the positive guard. For the library record, add one near-miss that exposes assuming all user classes inherit the same single-positional behaviour. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers assuming all user classes inherit the same single-positional behaviour.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Check the documented special cases and prefer explicit named attributes for user-defined classes.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny transport update with nested mappings for line, stop and delay. Include one ordinary case, one boundary and one deliberate failure caused by assuming all user classes inherit the same single-positional behaviour. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: Several built-in classes accept a single positional subpattern that matches the whole value, enabling concise type-and-value tests. It shows a trace, not only a final value. The ordinary case should demonstrate “The case checks that value is an int, captures the whole integer as n and then applies the positive guard.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Check the documented special cases and prefer explicit named attributes for user-defined classes. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
Patterns compose recursively, so nested sequences, mappings and class patterns can express a data schema directly. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is writing a deeply nested pattern that hides the first failing boundary. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Indent the expected shape as a tree and split validation into stages when the pattern becomes difficult to explain.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
match event:
case {'type':'reading','data':{'value':v,'unit':u}}:
use(v,u)Explained result. Both mapping levels and all required keys must match before v and u are available. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: homework message. Contrast the rule using a command name, subject code and optional due date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Patterns compose recursively, so nested sequences, mappings and class patterns can express a data schema directly.” Apply this procedure: Indent the expected shape as a tree and split validation into stages when the pattern becomes difficult to explain. The expected mechanism is: Both mapping levels and all required keys must match before v and u are available. For the homework message, add one near-miss that exposes writing a deeply nested pattern that hides the first failing boundary. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: library record. Stress-test the rule using a mapping with title, format and borrowing state. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Patterns compose recursively, so nested sequences, mappings and class patterns can express a data schema directly.” Apply this procedure: Indent the expected shape as a tree and split validation into stages when the pattern becomes difficult to explain. The expected mechanism is: Both mapping levels and all required keys must match before v and u are available. For the library record, add one near-miss that exposes writing a deeply nested pattern that hides the first failing boundary. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: CCA attendance. Explain the rule using tagged tuples for present, absent and late records. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Patterns compose recursively, so nested sequences, mappings and class patterns can express a data schema directly.” Apply this procedure: Indent the expected shape as a tree and split validation into stages when the pattern becomes difficult to explain. The expected mechanism is: Both mapping levels and all required keys must match before v and u are available. For the CCA attendance, add one near-miss that exposes writing a deeply nested pattern that hides the first failing boundary. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: science reading. Transfer the rule using a class with quantity, unit and validity flag. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Patterns compose recursively, so nested sequences, mappings and class patterns can express a data schema directly.” Apply this procedure: Indent the expected shape as a tree and split validation into stages when the pattern becomes difficult to explain. The expected mechanism is: Both mapping levels and all required keys must match before v and u are available. For the science reading, add one near-miss that exposes writing a deeply nested pattern that hides the first failing boundary. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers writing a deeply nested pattern that hides the first failing boundary.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Indent the expected shape as a tree and split validation into stages when the pattern becomes difficult to explain.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny revision card with a status tag and a list of evidence items. Include one ordinary case, one boundary and one deliberate failure caused by writing a deeply nested pattern that hides the first failing boundary. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: Patterns compose recursively, so nested sequences, mappings and class patterns can express a data schema directly. It shows a trace, not only a final value. The ordinary case should demonstrate “Both mapping levels and all required keys must match before v and u are available.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Indent the expected shape as a tree and split validation into stages when the pattern becomes difficult to explain. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
A successful pattern establishes only the stated structural and guard conditions; it does not automatically validate every domain rule or reject extra mapping data. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is treating one matched case as proof the whole input is trustworthy. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. List unstated invariants and validate them explicitly at the appropriate boundary.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
case {'age': int(age)} if 0 <= age <= 120: ...Explained result. The pattern and guard establish an integer in the stated range, but they say nothing about other fields or data provenance. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: CCA attendance. Stress-test the rule using tagged tuples for present, absent and late records. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A successful pattern establishes only the stated structural and guard conditions; it does not automatically validate every domain rule or reject extra mapping data.” Apply this procedure: List unstated invariants and validate them explicitly at the appropriate boundary. The expected mechanism is: The pattern and guard establish an integer in the stated range, but they say nothing about other fields or data provenance. For the CCA attendance, add one near-miss that exposes treating one matched case as proof the whole input is trustworthy. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: science reading. Explain the rule using a class with quantity, unit and validity flag. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A successful pattern establishes only the stated structural and guard conditions; it does not automatically validate every domain rule or reject extra mapping data.” Apply this procedure: List unstated invariants and validate them explicitly at the appropriate boundary. The expected mechanism is: The pattern and guard establish an integer in the stated range, but they say nothing about other fields or data provenance. For the science reading, add one near-miss that exposes treating one matched case as proof the whole input is trustworthy. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: transport update. Transfer the rule using nested mappings for line, stop and delay. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A successful pattern establishes only the stated structural and guard conditions; it does not automatically validate every domain rule or reject extra mapping data.” Apply this procedure: List unstated invariants and validate them explicitly at the appropriate boundary. The expected mechanism is: The pattern and guard establish an integer in the stated range, but they say nothing about other fields or data provenance. For the transport update, add one near-miss that exposes treating one matched case as proof the whole input is trustworthy. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: revision card. Predict the rule using a status tag and a list of evidence items. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A successful pattern establishes only the stated structural and guard conditions; it does not automatically validate every domain rule or reject extra mapping data.” Apply this procedure: List unstated invariants and validate them explicitly at the appropriate boundary. The expected mechanism is: The pattern and guard establish an integer in the stated range, but they say nothing about other fields or data provenance. For the revision card, add one near-miss that exposes treating one matched case as proof the whole input is trustworthy. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers treating one matched case as proof the whole input is trustworthy.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “List unstated invariants and validate them explicitly at the appropriate boundary.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny quiz response with multiple answer shapes and a confidence value. Include one ordinary case, one boundary and one deliberate failure caused by treating one matched case as proof the whole input is trustworthy. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: A successful pattern establishes only the stated structural and guard conditions; it does not automatically validate every domain rule or reject extra mapping data. It shows a trace, not only a final value. The ordinary case should demonstrate “The pattern and guard establish an integer in the stated range, but they say nothing about other fields or data provenance.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: List unstated invariants and validate them explicitly at the appropriate boundary. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
CHAPTER 19 OF 20 . Transfer with judgment
19. Choosing match versus if and dispatch tables
Pattern matching is strongest when branching depends on decomposing several related shapes; simple predicates or key-to-function dispatch may be clearer elsewhere. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is using match merely because it is newer syntax. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Compare the number of shapes, nesting depth, shared actions and extension policy before choosing control flow.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
handler = handlers.get(command)
if handler:
handler(payload)Explained result. A dispatch table can be clearer when one key selects an action and no structural decomposition is needed. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: transport update. Explain the rule using nested mappings for line, stop and delay. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Pattern matching is strongest when branching depends on decomposing several related shapes; simple predicates or key-to-function dispatch may be clearer elsewhere.” Apply this procedure: Compare the number of shapes, nesting depth, shared actions and extension policy before choosing control flow. The expected mechanism is: A dispatch table can be clearer when one key selects an action and no structural decomposition is needed. For the transport update, add one near-miss that exposes using match merely because it is newer syntax. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: revision card. Transfer the rule using a status tag and a list of evidence items. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Pattern matching is strongest when branching depends on decomposing several related shapes; simple predicates or key-to-function dispatch may be clearer elsewhere.” Apply this procedure: Compare the number of shapes, nesting depth, shared actions and extension policy before choosing control flow. The expected mechanism is: A dispatch table can be clearer when one key selects an action and no structural decomposition is needed. For the revision card, add one near-miss that exposes using match merely because it is newer syntax. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: quiz response. Predict the rule using multiple answer shapes and a confidence value. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Pattern matching is strongest when branching depends on decomposing several related shapes; simple predicates or key-to-function dispatch may be clearer elsewhere.” Apply this procedure: Compare the number of shapes, nesting depth, shared actions and extension policy before choosing control flow. The expected mechanism is: A dispatch table can be clearer when one key selects an action and no structural decomposition is needed. For the quiz response, add one near-miss that exposes using match merely because it is newer syntax. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: file event. Contrast the rule using a path action with optional metadata. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Pattern matching is strongest when branching depends on decomposing several related shapes; simple predicates or key-to-function dispatch may be clearer elsewhere.” Apply this procedure: Compare the number of shapes, nesting depth, shared actions and extension policy before choosing control flow. The expected mechanism is: A dispatch table can be clearer when one key selects an action and no structural decomposition is needed. For the file event, add one near-miss that exposes using match merely because it is newer syntax. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers using match merely because it is newer syntax.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Compare the number of shapes, nesting depth, shared actions and extension policy before choosing control flow.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny file event with a path action with optional metadata. Include one ordinary case, one boundary and one deliberate failure caused by using match merely because it is newer syntax. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: Pattern matching is strongest when branching depends on decomposing several related shapes; simple predicates or key-to-function dispatch may be clearer elsewhere. It shows a trace, not only a final value. The ordinary case should demonstrate “A dispatch table can be clearer when one key selects an action and no structural decomposition is needed.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Compare the number of shapes, nesting depth, shared actions and extension policy before choosing control flow. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
CHAPTER 20 OF 20 . Transfer with judgment
20. A systematic debugging and mastery route
Reliable matching comes from a subject inventory, ordered pattern table, controlled near-misses and tests for captures, guards and fallback behaviour. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is debugging only inside the selected body while ignoring why earlier patterns failed. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Reduce the subject, test one case at a time, log types and shapes, then restore order and add regression examples.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
def classify(x):
match x:
case {'kind':'note','text':str(t)} if t.strip(): return 'note'
case _: return 'other'Explained result. The test set should include a valid note, blank text, non-string text, a missing key and an extra harmless key, with each result explained. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: quiz response. Transfer the rule using multiple answer shapes and a confidence value. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Reliable matching comes from a subject inventory, ordered pattern table, controlled near-misses and tests for captures, guards and fallback behaviour.” Apply this procedure: Reduce the subject, test one case at a time, log types and shapes, then restore order and add regression examples. The expected mechanism is: The test set should include a valid note, blank text, non-string text, a missing key and an extra harmless key, with each result explained. For the quiz response, add one near-miss that exposes debugging only inside the selected body while ignoring why earlier patterns failed. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: file event. Predict the rule using a path action with optional metadata. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Reliable matching comes from a subject inventory, ordered pattern table, controlled near-misses and tests for captures, guards and fallback behaviour.” Apply this procedure: Reduce the subject, test one case at a time, log types and shapes, then restore order and add regression examples. The expected mechanism is: The test set should include a valid note, blank text, non-string text, a missing key and an extra harmless key, with each result explained. For the file event, add one near-miss that exposes debugging only inside the selected body while ignoring why earlier patterns failed. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: homework message. Contrast the rule using a command name, subject code and optional due date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Reliable matching comes from a subject inventory, ordered pattern table, controlled near-misses and tests for captures, guards and fallback behaviour.” Apply this procedure: Reduce the subject, test one case at a time, log types and shapes, then restore order and add regression examples. The expected mechanism is: The test set should include a valid note, blank text, non-string text, a missing key and an extra harmless key, with each result explained. For the homework message, add one near-miss that exposes debugging only inside the selected body while ignoring why earlier patterns failed. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: library record. Stress-test the rule using a mapping with title, format and borrowing state. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Reliable matching comes from a subject inventory, ordered pattern table, controlled near-misses and tests for captures, guards and fallback behaviour.” Apply this procedure: Reduce the subject, test one case at a time, log types and shapes, then restore order and add regression examples. The expected mechanism is: The test set should include a valid note, blank text, non-string text, a missing key and an extra harmless key, with each result explained. For the library record, add one near-miss that exposes debugging only inside the selected body while ignoring why earlier patterns failed. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers debugging only inside the selected body while ignoring why earlier patterns failed.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Reduce the subject, test one case at a time, log types and shapes, then restore order and add regression examples.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny homework message with a command name, subject code and optional due date. Include one ordinary case, one boundary and one deliberate failure caused by debugging only inside the selected body while ignoring why earlier patterns failed. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: Reliable matching comes from a subject inventory, ordered pattern table, controlled near-misses and tests for captures, guards and fallback behaviour. It shows a trace, not only a final value. The ordinary case should demonstrate “The test set should include a valid note, blank text, non-string text, a missing key and an extra harmless key, with each result explained.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Reduce the subject, test one case at a time, log types and shapes, then restore order and add regression examples. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
Parent guide: choose the next useful step
Start with evidence, not a label such as careless. Ask for one prediction and one trace. If the first transition is wrong, rebuild the model. If the model is sound but syntax fails, practise reference use. If routine cases are correct but boundaries fail, vary ties, defaults, unsupported inputs, ownership or missing paths. If explanations transfer, move to a small project.
Keep a weekly record with four lines: concept, prediction, observed difference and next test. Stop when fatigue replaces reasoning. A smaller case tomorrow is more useful than another hour of copying tonight.
Seek specialist help when cause and effect remain invisible after examples are reduced, when accessibility or data-loss implications are unclear, or when an important repository, database or application state may be at risk. Good support should make the learner’s reasoning more independent.
Capstone practice with explained routes
1. homework message: model, boundary and recovery
Create a small homework message using a command name, subject code and optional due date. Combine “The subject-and-cases mental model” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: A match statement evaluates its subject once, then tries case blocks from top to bottom until the first pattern and guard succeed. Apply: Write the subject value, list the cases in order and annotate the first structural test each case performs. Verify: The first case needs a two-item sequence whose first item equals ‘done’; otherwise the wildcard fallback runs. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
2. library record: model, boundary and recovery
Create a small library record using a mapping with title, format and borrowing state. Combine “Wildcard patterns” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: The underscore wildcard matches without binding a usable name, making it suitable for ignored positions and explicit fallbacks. Apply: Choose underscore when the value has no later role and place a broad fallback last. Verify: The third element may be anything and is deliberately not retained. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
3. CCA attendance: model, boundary and recovery
Create a small CCA attendance using tagged tuples for present, absent and late records. Combine “Mapping patterns” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: A mapping pattern asks for specified keys and applies subpatterns to their values; extra keys are normally allowed. Apply: List required keys separately from permitted extras and use a rest capture only when extras matter. Verify: The required keys must exist with matching values; unrelated keys do not by themselves make the case fail. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
4. science reading: model, boundary and recovery
Create a small science reading using a class with quantity, unit and validity flag. Combine “Positional class patterns and __match_args__” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: Positional class patterns are translated using the class __match_args__ contract, so position is an API decision rather than a visual guess. Apply: Inspect __match_args__ and prefer keyword patterns when field meaning should remain explicit. Verify: The pattern checks x against zero and captures y because the class explicitly publishes that positional order. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
5. transport update: model, boundary and recovery
Create a small transport update using nested mappings for line, stop and delay. Combine “Guards refine successful patterns” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: A guard runs only after its pattern succeeds and its captures are available; a false guard continues with later cases. Apply: Keep guards short and pure, and separate structural eligibility from an additional boolean policy. Verify: Both cases require score; the guard decides which body handles scores at or above 75. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
6. revision card: model, boundary and recovery
Create a small revision card using a status tag and a list of evidence items. Combine “Built-in class patterns” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: Several built-in classes accept a single positional subpattern that matches the whole value, enabling concise type-and-value tests. Apply: Check the documented special cases and prefer explicit named attributes for user-defined classes. Verify: The case checks that value is an int, captures the whole integer as n and then applies the positive guard. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
7. quiz response: model, boundary and recovery
Create a small quiz response using multiple answer shapes and a confidence value. Combine “Choosing match versus if and dispatch tables” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: Pattern matching is strongest when branching depends on decomposing several related shapes; simple predicates or key-to-function dispatch may be clearer elsewhere. Apply: Compare the number of shapes, nesting depth, shared actions and extension policy before choosing control flow. Verify: A dispatch table can be clearer when one key selects an action and no structural decomposition is needed. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
8. file event: model, boundary and recovery
Create a small file event using a path action with optional metadata. Combine “Literal patterns” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: Literal patterns compare the subject with a stated literal, using equality semantics except for the singleton checks involving None, True and False. Apply: Use a quoted literal, a singleton or a qualified value for a fixed target; test a near-miss of the same type. Verify: The string ‘ready’ and the singleton None are tests, not new variable bindings. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
Frequently asked questions
How long should a practice session be?
Use one complete prediction–observation–explanation cycle while attention remains good. Ten to twenty focused minutes can be enough.
Should every option or function be memorised?
No. Memorise the governing distinctions and practise retrieving the official reference. Understanding means predicting and explaining, not reciting a parameter list.
What if the result is correct but the explanation is weak?
Treat it as partial success. Ask for a trace and change one boundary. A reliable model survives controlled variation.
Is the shortest solution the best?
Not automatically. Prefer the solution whose semantics, failure modes and maintenance cost are easiest to justify for the actual project.
When should official documentation be used?
Use it whenever syntax, supported types, SQL dialect behaviour or Git version details matter. Primary documentation settles the current contract.
How can a parent help without technical expertise?
Ask what was predicted, where the first difference appeared, what evidence matters and which smaller example could isolate it.
How do we test transfer?
Change the context, vocabulary and one boundary. Require the learner to identify the invariant before using a tool.
What should be saved after practice?
Keep the corrected rule, one trace, one boundary case and the next question. Avoid storing pages of unexplained output.
Can these exercises replace backups?
No. Use disposable examples and proper backups. Learning should not endanger schoolwork, repositories or personal data.
What counts as mastery?
The learner can predict, verify, diagnose, recover and justify a choice across more than one context, while knowing when to consult the current reference.

