examples/gallery/02-tokens.hero
Un valore che può assumere forme diverse e un match per gestirle tutte.
- 53 righe
match deve gestire ogni forma possibile, altrimenti il programma non compila. Per questo tipo di valore non puoi usare un ramo generico che accetti tutto. Se aggiungi una forma, il compilatore segnala ogni match da aggiornare.
Eseguilo
Questo esempio serve a illustrare il linguaggio. Qui trovi il programma e non un risultato: non ci sono ancora test che confrontino il suo output byte per byte.
Il programma
## Tokens
#
# A variant with payloads, and the only construct that takes one apart.
# `match` is exhaustive or the program does not compile, and `_` is
# forbidden on a variant — adding a case has to break something.
variant Token
number
value: i64
word
text: str
plus
times
open
close
# What a token is called in a message.
function name_of(t: Token) -> str
return match t
.number _ => "a number"
.word _ => "a word"
.plus => "`+`"
.times => "`*`"
.open => "`(`"
.close => "`)`"
# Binding power, strongest first (§4.14's table, in miniature).
function power_of(t: Token) -> i64
return match t
.times => 2
.plus => 1
.number _ => 0
.word _ => 0
.open | .close => 0
function is_operator(t: Token) -> bool
return match t
.plus | .times => true
.number _ | .word _ | .open | .close => false
test "every token has a name and a power"
assert name_of(.plus) == "`+`"
assert power_of(.times) > power_of(.plus)
assert is_operator(.number(value: 7)) == false
function main()
# The annotation is required and it is not ceremony: a case says which
# case it is, never which variant, so a literal list of them has nothing
# to infer from. Name the type once and the whole list is checked.
line: [Token] = [.open, .number(value: 12), .plus, .word(text: "x"), .close]
for t in line
print(name_of(t))
impronta sha256 2862b0a6f461 · 1 file · index.json
Successivo: 03-fallible. Tutti gli esempi. ← Precedente: 01-points
Eseguine uno: i quattro comandi. Impara il linguaggio, oppure leggi la specifica completa in un solo file.