#1254 22.10.2022 14:53 AP
Schummler: Binding Operators

OCaml Binding Operators

OCaml Manual / Language Extensions / Binding Operators

let* Monadic Binding Operator

Example (based on OCaml has some new shiny syntax):

let safe_head = function
  | [] -> Result.Error "Empty list -> empty head."
  | hd :: _ -> Result.Ok hd

let safe_tail = function
  | [] -> Result.Error "Empty list -> empty tail."
  | _ :: [] -> Result.Error "Empty tail."
  | _ :: tl -> Result.Ok tl

let safe_div f1 f2 =
  if f2 = 0.0 then Result.Error "Division by zero."
  else Result.Ok (f1 /. f2)

let (let*) x f = Result.bind x f

let div_first_two xs =
  let* x = safe_head xs in
  let* ys = safe_tail xs in
  let* y = safe_head ys in
  safe_div x y  

Infix alternative: >>=

let+ Map Binding Operator

Example (source Craigfe / Operator Lookup):

# let ( >>| ) x f = List.map f x in
  [ 1; 2; 3 ] >>| fun elt -> elt * 2

- : int list = [ 2; 4; 6 ]

(* ——— is equivalent to: ———————————————————————————————— *)

# let ( let+ ) x f = List.map f x in
  let+ elt = [ 1; 2; 3 ] in
  elt * 2

- : int list = [ 2; 4; 6 ]

Infix alternative: >>| or >|= (Lwt)

let@ Function Application Binding Operator

Example (source The attack of the binding operators: introduce (let@) in the compiler codebase):

let copy_file src dest =
  let@ ic = with_input_file ~bin:true src in
  let@ oc = with_output_file ~bin:true dest in
  copy_chan ic oc

Infix alternative: @@


[->/]