Option en F#
La ausencia deletreada Some o None — no hay null que olvidar.
// Option makes absence explicit: Some value or None, no nulls.
let findQueen hive =
match hive with
| "Willow" -> Some 2024
| "Bramble" -> Some 2023
| _ -> None
let report hive =
match findQueen hive with
| Some year -> sprintf "%s: queen from %d" hive year
| None -> sprintf "%s: queenless!" hive
["Willow"; "Thistle"] |> List.iter (report >> printfn "%s")
// The Option module maps and defaults without unwrapping by hand.
let age = findQueen "Bramble" |> Option.map (fun y -> 2026 - y)
printfn "Queen age: %d" (age |> Option.defaultValue 0)
Cómo funciona
Some 2024yNoneson las únicas dos formas.- Matchear obliga a manejar ambos casos.
Option.mapydefaultValueencadenan sin desenvolver.
Palabras clave y builtins usados aquí
funletmatchwith
El intento, en números
- Líneas
- 17
- Caracteres a escribir
- 547
- Tokens
- 109
- Ritmo de tres estrellas
- 65 tpm
Al ritmo de tres estrellas de 65 tokens por minuto, este intento toma unos 101 segundos.
Paso 2 de 3 en Coincidencia de patrones; paso 8 de 27 en Fundamentos del lenguaje.