我是OCaml的新手,并尝试调试一些OCaml代码.OCaml中的任何函数是否等同toString()于Java中的函数,通过它可以将大多数对象打印为输出?
Pervasives模块中有一些函数,如string_of_int,string_of_float,string_of_bool(您不必打开Pervasives模块,因为它是......普遍存在的).
或者,您可以使用Printf执行此类输出.例如:
let str = "bar" in
let num = 1 in
let flt = 3.14159 in
Printf.printf "The string is: %s, num is: %d, float is: %f" str num flt
Run Code Online (Sandbox Code Playgroud)
在Printf模块中还有一个sprintf函数,所以如果你只想创建一个字符串而不是打印到stdout,你可以用以下代码替换最后一行:
let output = Printf.sprintf "The string is: %s, num is: %d, float is: %f" str num flt
Run Code Online (Sandbox Code Playgroud)
为了你自己定义的更复杂的数据类型,你可以使用导出扩展,使您woudn't需要定义你的类型你自己的漂亮的打印机功能.
如果你使用 Core 和相关的 Sexplib 语法扩展,有很好的解决方案。本质上,sexplib 自动生成 OCaml 类型和 s 表达式之间的转换器,提供方便的序列化格式。
这是使用 Core 和 Utop 的示例。请确保按照以下说明进行设置以使用 Core:http : //realworldocaml.org/install
utop[12]> type foo = { x: int
; y: string
; z: (int * int) list
}
with sexp;;
type foo = { x : int; y : string; z : (int * int) list; }
val foo_of_sexp : Sexp.t -> foo = <fun>
val sexp_of_foo : foo -> Sexp.t = <fun>
utop[13]> let thing = { x = 3; y = "hello"; z = [1,1; 2,3; 4,2] } ;;
val thing : foo = {x = 3; y = "hello"; z = [(1, 1); (2, 3); (4, 2)]}
utop[14]> sexp_of_foo thing;;
- : Sexp.t = ((x 3) (y hello) (z ((1 1) (2 3) (4 2))))
utop[15]> sexp_of_foo thing |> Sexp.to_string_hum;;
- : string = "((x 3) (y hello) (z ((1 1) (2 3) (4 2))))"
Run Code Online (Sandbox Code Playgroud)
您还可以使用以下内联引号语法为未命名类型生成 sexp 转换器。
utop[18]> (<:sexp_of<int * float list>> (3,[4.;5.;6.]));;
- : Sexp.t = (3 (4 5 6))
Run Code Online (Sandbox Code Playgroud)
此处提供更多详细信息:https : //realworldocaml.org/v1/en/html/data-serialization-with-s-expressions.html
| 归档时间: |
|
| 查看次数: |
2800 次 |
| 最近记录: |