Pular para o conteúdo

Padrões Básicos: Literais, Curinga e Binding

Nesta página

Todo padrão em Zolo é composto por três primitivas fundamentais. Entendê-las é o primeiro passo para dominar o sistema de padrões da linguagem.

Padrões literais

Um padrão literal casa quando o valor é exatamente igual ao literal escrito. Funciona com inteiros, floats, strings, booleans, negativos — qualquer tipo com igualdade. O braço _ ao final torna o match exaustivo.

Literais inteiros, de string, booleanos e negativos em padrões.

01-literal-patterns.zolo
Playground
// Feature: Literal patterns — match by exact equality

// Syntax: `match x { 1 => ..., "a" => ..., true => ... }`

// When to use: discriminate by concrete value. Works with ints,

// floats, strings, bools, nil — anything with equality.


let n = 2
let name = match n {
  1 => "one",
  2 => "two",
  3 => "three",
  _ => "other",
}
print(name)  // two


// String literal.

let cmd = "help"
let response = match cmd {
  "help" => "showing help",
  "quit" => "exiting",
  "version" => "version 1.0",
  _ => "unknown command",
}
print(response)  // showing help


// Bool literal — exhaustive bool match without needing `_`.

let active = true
let label = match active {
  true => "ON",
  false => "OFF",
}
print(label)  // ON


// Negative literal.

let temp = -5
let kind = match temp {
  -10 => "very cold",
  -5 => "cold",
  0 => "freezing point",
  _ => "other",
}
print(kind)  // cold

// expected:

// two

// showing help

// ON

// cold

Curinga _

O curinga _ casa com qualquer valor sem capturá-lo. Use-o quando você precisa cobrir o caso restante mas não vai usar o valor no corpo do braço. É a forma mais eficiente de tornar um match exaustivo.

_ como catch-all sem criar uma variável.

03-wildcard.zolo
Playground
// Feature: Wildcard `_` — matches anything, discards the value

// Syntax: `match x { ... _ => ... }`

// When to use: catch-all that does NOT need the value. Useful to

// make a match exhaustive without naming the variable.


let n = 99
let label = match n {
  0 => "zero",
  1 => "one",
  _ => "other",
}
// doesn't name n

print(label)  // other


// Wildcard as a guard against unenumerated values.

let cmd = "shutdown"
let r = match cmd {
  "start" => "starting",
  "stop" => "stopping",
  _ => "ignored",
}
print(r)  // ignored


// Difference vs binding: `_` cannot be used in the arm body.

// When you want to read the value, prefer binding (`n =>`).

let x = 10
let kind = match x {
  1 | 2 | 3 => "small",
  _ => "large",
}
print(kind)  // large

// expected:

// other

// ignored

// large

Binding: capturar o valor

Um binding substitui o _ quando você precisa do valor no corpo do braço. Qualquer identificador (por exemplo, n, other, name) que não seja uma variante de enum age como binding: casa sempre e vincula o valor ao nome.

n => captura o valor; other => como catch-all nomeado.

02-binding-pattern.zolo
Playground
// Feature: Binding pattern — capture the value in a name

// Syntax: `match x { name => ... }` — any identifier

// When to use: capture the value that matched to use it in the arm.


let x = 42

// Simple binding — `n` receives x. Always matches, so it must come

// last (or be the only arm).

let msg = match x {
  n => "got {n}",
}
print(msg)  // got 42


// Combined with literals — binding is the catch-all that replaces

// `_` when you need the value.

let y = 7
let label = match y {
  1 => "one",
  2 => "two",
  other => "other ({other})",
}
print(label)  // other (7)


// Binding in a string match.

let s = "zolo"
let r = match s {
  "rust" => "systems language",
  name => "a language called {name}",
}
print(r)  // a language called zolo

// expected:

// got 42

// other (7)

// a language called zolo

Desafio

No exemplo de binding, adicione um braço 0 => "zero" antes do binding e verifique a ordem: o braço literal tem prioridade sobre o catch-all.

Veja também

Buscar no Zolo

9 resultados

enespt-br