【问题标题】:toString() equivalent in OCamlOCaml 中的 toString() 等效项
【发布时间】:2013-11-20 17:52:00
【问题描述】:

我是 OCaml 的新手,正在尝试调试一些 OCaml 代码。 OCaml 中是否有任何等效于 Java 中的 toString() 函数的函数,通过它可以将大多数对象打印为输出?

【问题讨论】:

  • 这是 OCaml 的致命弱点。答案可能取决于您使用的是 Core 还是 Batteries

标签: ocaml


【解决方案1】:

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 函数,因此如果您只想创建一个字符串而不是打印到标准输出,您可以将最后一行替换为:

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

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

【讨论】:

  • Sexplib 库也很有用。
【解决方案2】:

如果您使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-08
    • 2010-09-06
    • 1970-01-01
    相关资源
    最近更新 更多