result in OCaml
Ok or Error, with bind to keep the pipeline on the happy track.
(* result carries Ok or Error; bind keeps the pipeline honest. *)
let parse_depth raw =
match int_of_string_opt raw with
| Some cm -> Ok cm
| None -> Error ("unreadable: " ^ raw)
let classify cm =
if cm < 10 then Error (Printf.sprintf "%d cm is a puddle" cm)
else Ok (Printf.sprintf "%d cm accepted" cm)
let () =
["65"; "n/a"; "4"]
|> List.map (fun raw -> Result.bind (parse_depth raw) classify)
|> List.iter (function
| Ok note -> print_endline ("OK: " ^ note)
| Error why -> print_endline ("SKIP: " ^ why))
How it works
int_of_string_optstarts the chain without exceptions.Result.bindchains steps; the first Error short-circuits.- A
functionmatch unpacks whichever side arrived.
Keywords and builtins used here
ErrorNoneOkSomeelsefunfunctionifletmatchthenwith
The run, in numbers
- Lines
- 16
- Characters to type
- 510
- Tokens
- 124
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 124 seconds.
Step 1 of 3 in Idioms, step 24 of 29 in Language basics.