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)
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] ).
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With