typestar

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

  1. Some 2024 y None son las únicas dos formas.
  2. Matchear obliga a manejar ambos casos.
  3. Option.map y defaultValue encadenan sin desenvolver.

Palabras clave y builtins usados aquí

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.

Escribe este fragmento

Paso 2 de 3 en Coincidencia de patrones; paso 8 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →

Option en otros lenguajes