// DOCS NAVIGATION
Pattern Matching — match_
SOURCE: content/docs/reference/04-avancado.md — 04 Avançado / 1. Pattern Matching — match
Conceito / Concept
PT-BR:
match é a construção de correspondência de padrões do SpectraLang. Ela compara um valor contra uma série de padrões e executa o corpo do primeiro padrão que corresponder. O compilador verifica exaustividade — todos os casos possíveis devem ser cobertos, ou um padrão curinga _ deve ser incluído.
EN-US:
match is SpectraLang's pattern matching construct. It compares a value against a series of patterns and executes the body of the first matching pattern. The compiler checks exhaustiveness — all possible cases must be covered, or a wildcard _ pattern must be included.
Sintaxe / Syntax
match expressão {
when padrão1 then corpo1,
when padrão2 then corpo2,
otherwise then corpo_padrão // curinga / wildcard
}
Padrões Literais / Literal Patterns
module match_demo
from std.io import println
public func main() {
let x = 5
let resultado = match x {
when 1 then "um",
when 2 then "dois",
when 3 then "três",
when 4 then "quatro",
when 5 then "cinco",
otherwise then "outro"
}
println(resultado)
// "cinco"
}
Padrões de Identificador / Identifier Patterns (Binding)
PT-BR:
Um identificador em um padrão captura o valor e o vincula a um nome para uso no corpo do braço.
EN-US:
An identifier in a pattern captures the value and binds it to a name for use in the arm body.
func descrever(n: int) returns string {
match n {
when 0 then "zero",
when x then f"o número {x}" // x captura o valor / x captures the value
}
}
Padrões de Variante de Enum / Enum Variant Patterns
Variantes Unitárias / Unit Variants
enum Cor { Vermelho, Verde, Azul }
func nome_da_cor(c: Cor) returns string {
match c {
when Cor::Vermelho then "Vermelho",
when Cor::Verde then "Verde",
when Cor::Azul then "Azul"
}
}
Variantes com Dados Tuple / Tuple Variant Patterns
enum Mensagem {
Sair,
Mover(int, int),
Texto(string)
}
func processar(msg: Mensagem) {
match msg {
when Mensagem::Sair then println("Saindo..."),
when Mensagem::Mover(x, y) then println(f"Movendo para ({x}, {y})"),
when Mensagem::Texto(t) then println(f"Mensagem: {t}")
}
}
Variantes com Campos Nomeados / Struct-Style Variant Patterns
enum Forma {
Circulo { raio: float },
Retangulo { largura: float, altura: float }
}
func calcular_area(f: Forma) returns float {
match f {
when Forma::Circulo { raio } then raio * raio * 3.14159,
when Forma::Retangulo { largura, altura } then largura * altura
}
}
Renomeação de Campos / Field Renaming in Patterns
enum Ponto3D {
Cartesiano { x: float, y: float, z: float }
}
match ponto {
when Ponto3D::Cartesiano { x: a, y: b, z: c } then {
// a, b, c são os valores de x, y, z
println(f"({a}, {b}, {c})")
}
}
Padrão Curinga / Wildcard Pattern _
PT-BR:
_ captura qualquer valor e o descarta. É obrigatório quando não são listados todos os casos.
EN-US:
_ captures any value and discards it. It is required when not all cases are listed.
let c = Cor::Azul
match c {
when Cor::Vermelho then println("Vermelho!"),
otherwise then println("Não é vermelho.") // captura Verde e Azul / captures Green and Blue
}
Corpo de Bloco / Block Body
func processar_forma(f: Forma) returns float {
match f {
when Forma::Circulo { raio } then {
let area = raio * raio * 3.14159
println(f"Círculo com raio {raio}")
area // retorno implícito do bloco / implicit block return
}
when Forma::Retangulo { largura, altura } then {
let area = largura * altura
println(f"Retângulo {largura}x{altura}")
area
}
}
}
match como Expression vs Statement
// Como expressão: retorna valor / As expression: returns value
let descricao = match x {
when 0 then "zero",
otherwise then "não-zero"
}
// Como statement: apenas efeitos colaterais / As statement: only side effects
match x {
when 0 then println("zero"),
otherwise then println("não-zero")
}
Exaustividade / Exhaustiveness
PT-BR:
O compilador verifica se todos os casos de um enum são cobertos. Se um caso estiver faltando, um erro de compilação é emitido. Use _ para cobrir os casos restantes.
EN-US:
The compiler checks whether all cases of an enum are covered. If a case is missing, a compilation error is emitted. Use _ to cover remaining cases.
enum Status { Ativo, Inativo, Pendente }
// ERRO: faltando Pendente / ERROR: missing Pendente
// match s {
// Status::Ativo => ...,
// Status::Inativo => ...
// }
// OK: todos os casos / OK: all cases
match s {
when Status::Ativo then "ativo",
when Status::Inativo then "inativo",
when Status::Pendente then "pendente"
}
// OK: com curinga / OK: with wildcard
match s {
when Status::Ativo then "ativo",
otherwise then "não ativo"
}