Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
  
like image 762
Greg Avatar asked May 26 '21 06:05

Greg


People also ask

What does :: do in OCaml?

It is usually used if you have a function or value that is very similar to some other, but is in some way new or modified. Regarding the :: symbol - as already mentioned, it is used to create lists from a single element and a list ( 1::[2;3] creates a list [1;2;3] ).

What is in keyword in OCaml?

As a matter of syntax, in is mostly acting like punctuation; it allows a parser for the language to tell where expr1 stops and expr2 begins.

Does OCaml have monads?

Monads in OCaml are generally used in a slightly different way than in other languages. Rather than using >>= for monadic binds, values are generally bound using a ppx with a syntax such as let%bind x = ... . Additionally, as of OCaml 4.08, the langauge itself contains syntax for calling monadic functions.


1 Answers

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

like image 134
X. Van de Woestyne Avatar answered Sep 27 '22 18:09

X. Van de Woestyne