如何在 OCaml 中组合函数的布尔值和单位输出?
How to combine boolean and unit output of functions in OCaml?
如果我通过例子解释我的意思会更容易。
那么我们如何编写一个以整数作为参数的函数,如果该数字大于 0 则它 return true
并打印 Good!
否则仅 returns false
?
有两种方法。第一个是通过提供一个验证答案的函数并使用函数“外部”的条件来分离问题。例如:
let is_valid n = n > 0
(* And after *)
if is_valid 10
then
print_endline "Good"
否则,可以在返回值之前显示结果,例如:
let is_valid n =
let result = n > 0 in
let () =
if result
then print_endline "Good!"
in result
在第二个例子中,无论如何都会返回最终结果(布尔值),但如果结果为“true”,函数将显示“Good!”。
如果我通过例子解释我的意思会更容易。
那么我们如何编写一个以整数作为参数的函数,如果该数字大于 0 则它 return true
并打印 Good!
否则仅 returns false
?
有两种方法。第一个是通过提供一个验证答案的函数并使用函数“外部”的条件来分离问题。例如:
let is_valid n = n > 0
(* And after *)
if is_valid 10
then
print_endline "Good"
否则,可以在返回值之前显示结果,例如:
let is_valid n =
let result = n > 0 in
let () =
if result
then print_endline "Good!"
in result
在第二个例子中,无论如何都会返回最终结果(布尔值),但如果结果为“true”,函数将显示“Good!”。