在OCaml的let命令(即let _ = ... in)中使用下划线通配符有什么副作用? [英] Any side effect of using underscore wildcard in let command (i.e., let _ = ... in) in OCaml?
问题描述
在使用OCaml时,我几乎总是在let _ = exp
中使用下划线通配符,尤其是当exp
的结果不重要,但其中的计算却很重要时.例如:
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
所以,我只是想知道是否广泛使用let _ = ...
有什么副作用?
So, I just wonder if there is any side effect of extensively using let _ = ...
?
推荐答案
副作用是将来会在您的软件中跟踪令人讨厌的错误. 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
并且将来您会在f
中添加一个参数:
And that in the future you add an argument to f
:
let f a b c = ...
表达式let _ = f 3 4
仍会静默编译,并且您的程序将不会调用该函数,这使您想知道正在发生什么.如果您需要忽略非单位结果,最好总是让()
并使用ignore
:
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"
使用let _ = ...
应该被认为是不好的风格.
Using let _ = ...
should be considered bad style.
这篇关于在OCaml的let命令(即let _ = ... in)中使用下划线通配符有什么副作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!