typestar

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

  1. int_of_string_opt starts the chain without exceptions.
  2. Result.bind chains steps; the first Error short-circuits.
  3. A function match unpacks whichever side arrived.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Idioms, step 24 of 29 in Language basics.

← Previous Next →