Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any side effect of using underscore wildcard in let command (i.e., let _ = ... in) in OCaml?

Tags:

let

ocaml

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 _ = ... ?

like image 992
Trung Ta Avatar asked Mar 14 '15 11:03

Trung Ta


Video Answer


3 Answers

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.

like image 80
Daniel Bünzli Avatar answered Sep 27 '22 21:09

Daniel Bünzli


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.

like image 27
Pascal Cuoq Avatar answered Sep 27 '22 21:09

Pascal Cuoq


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
like image 38
Jürgen Hötzel Avatar answered Sep 27 '22 21:09

Jürgen Hötzel