Result en F#
Ok o Error, y bind para mantener el pipeline en la vía feliz.
// Result carries Ok or Error; the pipeline stays on the happy track.
let parseWeight (raw: string) =
match System.Double.TryParse raw with
| true, kg -> Ok kg
| false, _ -> Error (sprintf "unreadable: %s" raw)
let classify kg =
if kg < 15.0 then Error (sprintf "%.1f kg is too light" kg)
else Ok (sprintf "%.1f kg accepted" kg)
// bind chains Result-returning steps; the first Error short-circuits.
["31.4"; "n/a"; "9.2"]
|> List.map (parseWeight >> Result.bind classify)
|> List.iter (function
| Ok note -> printfn "OK: %s" note
| Error why -> printfn "SKIP: %s" why)
Cómo funciona
Double.TryParsematchea como tupla de bool y valor.Result.bindencadena pasos; el primer Error corta.functionmatchea el valor del pipe sin nombrarlo.
Palabras clave y builtins usados aquí
elsefalsefunctionifletmatchstringthentruewith
El intento, en números
- Líneas
- 16
- Caracteres a escribir
- 571
- Tokens
- 119
- Ritmo de tres estrellas
- 60 tpm
Al ritmo de tres estrellas de 60 tokens por minuto, este intento toma unos 119 segundos.
Paso 1 de 3 en Idiomas del lenguaje; paso 19 de 27 en Fundamentos del lenguaje.