Saltar al contenido

Patrones Básicos: Literales, Comodín y Binding

En esta página

Todo patrón en Zolo está compuesto por tres primitivas fundamentales. Entenderlas es el primer paso para dominar el sistema de patrones del lenguaje.

Patrones literales

Un patrón literal coincide cuando el valor es exactamente igual al literal escrito. Funciona con enteros, floats, strings, booleanos, negativos — cualquier tipo con igualdad. La rama _ al final hace el match exhaustivo.

Literales enteros, de string, booleanos y negativos en patrones.

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

Comodín _

El comodín _ coincide con cualquier valor sin capturarlo. Úsalo cuando necesites cubrir el caso restante pero no vayas a usar el valor en el cuerpo de la rama. Es la forma más eficiente de hacer un match exhaustivo.

_ como catch-all sin crear una variable.

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 el valor

Un binding reemplaza el _ cuando necesitas el valor en el cuerpo de la rama. Cualquier identificador (por ejemplo, n, other, name) que no sea una variante de enum actúa como binding: siempre coincide y enlaza el valor al nombre.

n => captura el valor; other => como catch-all con nombre.

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

Desafío

En el ejemplo de binding, agrega una rama 0 => "zero" antes del binding y verifica el orden: la rama literal tiene prioridad sobre el catch-all.

Consulta también

Buscar en Zolo

9 resultados

enespt-br