ocamlmonadsdo-notation

Do Notation in OCaml


Does OCaml have an equivalent to Haskell's Do Notation?

Another way to put it - is there an easy way to handle nesting monadic operations more easily... cause this is annoying:

open Batteries
open BatResult.Infix

let () =
  let out = 
    (Ok("one")) >>=
      (fun a -> 
        let b = Ok("two") in
        b >>= (fun c -> 
          print_endline(a);
          print_endline(c);
          Ok(c)
          )) in
  ignore(out)
  

Solution

  • Yes, since OCaml 4.08, it is possible to describe let operators. For example:

    let (let*) x f = BatResult.bind x f 
    let (let+) x f = BatResult.map f x
    

    This makes it possible to write programs in a style close to the direct style:

    let out = 
      let* a = Ok "one" in 
      let* b = Ok "two" in 
      let () = print_endline a in 
      let () = print_endline b in 
      Ok b
    

    You can describe a large number of operators, for monads (e.g. let* for bind and let+ for map), for applicative (e.g. let+ for map and and+ for product (or zip)) etc.

    Otherwise it is possible to use syntax extensions, for example https://github.com/janestreet/ppx_let which, for the moment, offers even more possibilities than the let operators. If you ever want examples of let operators, in Preface (shameless plug), we define plenty of them!

    edit: As @ivg says, you can use any of $ ∣  & ∣  * ∣  + ∣  - ∣  / ∣  = ∣  > ∣  @ ∣  ^ ∣  | for defining your let or and operator.

    see: https://ocaml.org/manual/bindingops.html