In OCaml, we can replace this code:
let do_stuff1 () =
let () = print_endline "Step 1" in
let () = print_endline "Step 2" in
let () = print_endline "Step 3" in
print_endline "done"
With this one:
let do_stuff2 () =
()
; print_endline "Step 1"
; print_endline "Step 2"
; print_endline "Step 3"
; print_endline "done"
(forgive my unconventional style, I add a bogus unit at the start because I like the symmetrical look)
If allowed, I could have defined the ;
operator myself: I choose to use &
instead, for illustration purposes.
let do_stuff3 () =
let ( & ) a b =
let () = a in
b
in
()
& print_endline "Step 1"
& print_endline "Step 2"
& print_endline "Step 3"
& print_endline "done"
Playing with the let*
syntax, I notice I sometimes face the same pattern.
Whereas this would be the ātraditionalā style to work with monads and there isnāt much to say:
let compute =
let ( >>= ) = Result.bind in
res1 >>= fun () ->
res2 >>= fun () ->
res3 >>= fun () -> res4
We can also use this alternative syntax:
let compute =
let ( let* ) = Result.bind in
let* () = res1 in
let* () = res2 in
let* () = res3 in
res4
But this looks very similar to the reason why the semicolon operator was invented. Since I canāt override semicolon, I instead define the &
operator again, but this time it works in a monadic context.
let compute =
let ( let* ) = Result.bind in
let ( & ) a b =
let* () = a in
b
in
Ok ()
& res1
& res2
& res3
& res4
Again, I add a bogus Ok ()
for symmetry, but we could of course write this code as:
res1 &
res2 &
res3 &
res4
Has this been given any thought? I feel that there is something missing to the let*
syntax. We āshouldā have a semicolon-equivalent operator that could work in a monadic context.