Missing values and errors · Coding Class
This topic is not available in the selected language or version. Showing the start of this section.
Apply the chapter in three steps: an exercise, a program project, and a debugging task. Implement first, then consult the hints and completion criteria. Use a separate file or working directory for each task.
1. Exercise · Handle a missing value
Section titled “1. Exercise · Handle a missing value”Write a function taking Option<Int> and returning the number as a string for Some, or missing for None.
Completion: Some(0) gives 0, Some(42) gives 42, and a typed None gives missing.
Hint: Zero is a present value, distinct from None.
2. Build a program · Build a number converter
Section titled “2. Build a program · Build a number converter”Use double_number from the chapter to process [“21”, “hello”, “-2”] in order. Print invalid on invalid input and continue.
Completion: Output is 42, invalid, -4, and the program exits successfully.
Hint: Match each Result in the loop; handle invalid input without ending main.
3. Debug · Fix ? in main
Section titled “3. Debug · Fix ? in main”The main below does not return Result. Replace the use of ? with a match handling success and failure in main.
Start with this deliberately broken program.
use std.convert as convert;fn main() { let value = convert.parse_int("21")?; println(value);}xen check class_question.xenDiagnostic excerpt:
current function return type must be Result<T,E>Completion: Input 21 prints 21; hello prints invalid. Keep main’s return type unchanged.
Hint: ? propagates errors only inside a Result-returning function with the same error type.
Verify and record
Section titled “Verify and record”Use xen check file.xen followed by xen run file.xen for ordinary programs; use xen test file.xen for test-only files. Record the original error, its cause, and the corrected result, then rerun every input in the completion criteria.