When using OCaml, I almost always use underscore wildcard in let _ = exp
, especially when the result of exp
is not important, but the computation inside it is. For example:
let _ = print_endline "abc" in ... let _ = a := !a + 1 in ... let _ = do_some_thing ... in
So, I just wonder if there is any side effect of extensively using let _ = ...
?
The side effect is annoying bugs to track in your software in the future. The problem with let _ =
is that it will silently ignore partial applications you intended to be total. Suppose you write the following:
let f a b = ...
let _ = f 3 4
And that in the future you add an argument to f
:
let f a b c = ...
The expression let _ = f 3 4
will still silently compile and your program will not invoke the function, leaving you wondering what is happening. It is much better to always let to ()
and use ignore
when if you need to ignore a non unit result:
let () = ignore (f 3 4)
let () = print_endline "abc"
Using let _ = ...
should be considered bad style.
No, there is absolutely no consequence to using let _ =
extensively. The compiler does not add a name to the global environment since you didn't give one.
The purpose of let
is to bind values to identifiers. If you doing side-effects only it's its better to wrap it in a begin .. end
block. In your case:
begin
print_endline "abc";
a := !a + 1;
do_some_thing ();
end
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