typestar

Pipelines de Option en F#

map, filter y defaultValue encadenan maybes sin un solo chequeo de null.

// Option.map and bind chain maybes without a single null check.
let inventory = Map [ "Willow", 14; "Bramble", 3 ]

let jarsFor hive = inventory |> Map.tryFind hive

let shipping hive =
    hive
    |> jarsFor
    |> Option.filter (fun jars -> jars >= 6)
    |> Option.map (fun jars -> sprintf "%s ships %d jars" hive jars)
    |> Option.defaultValue (sprintf "%s holds its stock" hive)

["Willow"; "Bramble"; "Thistle"]
|> List.iter (shipping >> printfn "%s")

Cómo funciona

  1. Map.tryFind abre la cadena con un Option.
  2. Option.filter vuelve None una respuesta floja.
  3. defaultValue aterriza la cadena en tierra firme.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
14
Caracteres a escribir
441
Tokens
106
Ritmo de tres estrellas
65 tpm

Al ritmo de tres estrellas de 65 tokens por minuto, este intento toma unos 98 segundos.

Escribe este fragmento

Paso 3 de 3 en Idiomas del lenguaje; paso 21 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →