Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Enum-keyed table round trip

Closed enums remain typed values even though their runtime representation is a compact i32 tag. That makes them suitable for exhaustive dispatch and fast table keys.

; A closed enum can be used as a typed hash-table key and survives
; serialize/deserialize when the destination type is declared.

(enum Shape Rock Paper Scissors)

(sig points [[{ Shape Int }]])
(let points (Table/new))
(Table/set! Rock 1 points)
(Table/set! Scissors 2 points)

(let text (serialize points))

; `deserialize` needs a concrete expected type.
(sig restored [[{ Shape Int }]])
(let restored (deserialize text))

(let score (Table/get-unsafe Rock restored))

(match Rock
  Rock score
  Paper 0
  Scissors 0)

The runnable source is examples/demo/04-enum-table-round-trip.que. From a checkout, run it with:

que examples/demo/04-enum-table-round-trip.que --debug

The [[{ Shape Int }]] annotation is only needed because deserialize needs to know which decoder to generate. It is the current library representation of a table: buckets containing key/value tuples. Normal table code should keep using Table/new, Table/set!, Table/get*, and Table/get-unsafe rather than accessing that representation directly.

Enum serialization uses declared names (Rock, Paper, Scissors), and the decoder validates them against the expected enum. =~ compares values of this same enum; match checks coverage of its variants.