Prerequisite
СсылкаUse Topaz 5.21.3 with language mode 5.21 and the SELF compiler. Complete First checked and executed program first.
1. Build a value and handle its cases
СсылкаSave the source as data-. Ticket has named fields and a Status value. Construct a variant with Status.. Match it with case Open().
2. Check the program
СсылкаCheck the ticket program
Ссылкаimport std.ioenum Status { Open, Closed }record Ticket { title: string, status: Status }function describe(ticket: Ticket) -> string {let state = match (ticket.status) {case Open() => "open"case Closed() => "closed"}return "{ticket.title}: {state}"}let first = Ticket { title: "Docs", status: Status.Open() }let second = Ticket { title: "Tests", status: Status.Closed() }io.writeLine(describe(first))io.writeLine(describe(second))
data-and-patterns.tpz: types-ok (2 modules)
data-and-patterns.tpz: resolve-ok (2 modules)
Ожидаемый результат
Ожидаемый результат
Проверка принимает программу. Код завершения 0.
Наблюдаемые утверждения · Пройдено · 5.21.3
Код завершения 0.
data-and-patterns.tpz: types-ok (2 modules)data-and-patterns.tpz: resolve-ok (2 modules)
Нет вывода ошибок.
- Пройдено · expected 0; observed 0
Expect exit 0. If checking fails, follow the reported diagnostic, correct the source, and check again.
3. Run both cases
СсылкаPrint both ticket states
Ссылкаimport std.ioenum Status { Open, Closed }record Ticket { title: string, status: Status }function describe(ticket: Ticket) -> string {let state = match (ticket.status) {case Open() => "open"case Closed() => "closed"}return "{ticket.title}: {state}"}let first = Ticket { title: "Docs", status: Status.Open() }let second = Ticket { title: "Tests", status: Status.Closed() }io.writeLine(describe(first))io.writeLine(describe(second))
Docs: open
Tests: closed
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
Docs: openTests: closed
Наблюдаемые утверждения · Пройдено · 5.21.3
Код завершения 0.
Docs: openTests: closed
Нет вывода ошибок.
- Пройдено · expected 0; observed 0
- Пройдено · stdout matches the authored expectation
- Пройдено · stderr matches the authored expectation
The two calls exercise both cases used by describe.
Verification
СсылкаPublic Topaz 5.21.3 checked and ran this program successfully in Docs run 42224592687, attempt 2. The recorded exit codes and output were compared with this page's current product assertions. The fixture files, invocation and expected output were unchanged.
Records, enums and newtypes defines the declarations used here. Pattern matching defines variant patterns, case selection and match coverage.
Next steps
СсылкаContinue with Generic functions and protocols. For parameter and return syntax, use Functions and generics.