OCaml中的toString()等价物

时间:2013-11-20 17:52:00

标签: ocaml

我是OCaml的新手,并尝试调试一些OCaml代码。 OCaml中的任何函数是否等同于Java中的toString()函数,大多数对象都可以作为输出打印出来?

2 个答案:

答案 0 :(得分:9)

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 

在Printf模块中还有一个sprintf函数,所以如果你只想创建一个字符串而不是打印到stdout,你可以用以下代码替换最后一行:

let output = Printf.sprintf "The string is: %s, num is: %d, float is: %f" str num flt

对于您自己定义的更复杂的数据类型,您可以使用Deriving扩展名,这样您就不需要为您的类型定义自己的漂亮打印机功能。

答案 1 :(得分:4)

如果你使用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))))"

您还可以使用以下内联引用语法为未命名类型生成sexp转换器。

utop[18]> (<:sexp_of<int * float list>> (3,[4.;5.;6.]));;
- : Sexp.t = (3 (4 5 6))

此处提供了更多详细信息:https://realworldocaml.org/v1/en/html/data-serialization-with-s-expressions.html