OCaml:将bool转换/转换为int

hli*_*117 0 ocaml casting

如何将ocaml布尔值转换为整数?(没有int_of_bool功能.)

Ryt*_*nas 6

2020 年,您可以使用Bool.to_int. 来自 Bool 库文档:

val to_int : bool -> int
如果 b 为假,则 b 为 0;如果 b 为真,则 b 为 1。

来源:https ://caml.inria.fr/pub/docs/manual-ocaml/libref/Bool.html


Jef*_*eld 5

这是一个可能的实现:

let int_of_bool b = if b then 1 else 0
Run Code Online (Sandbox Code Playgroud)

图书馆OCaml Batteries Included to_int在其BatBool模块中具有功能.

  • @ hlin117:从概念上讲,没有理由说布尔值和整数是可转换的.为什么是真的1?为什么假0?为什么不是其他一些号码?除了那些整数是C中的比较运算符的结果之外,我可以想到没有理由,这与OCaml非常无关. (3认同)