ocaml - OCaml 中的 toString() 等效项

标签 ocaml

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

最佳答案

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扩展,这样您就不需要为您的类型定义自己的 pretty-print 函数。

关于ocaml - OCaml 中的 toString() 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20103275/

相关文章:

ocaml - 如何在 OCaml 中定义 "apply"

ocaml - 为具有泛型类型参数的多态变体编写类型约束

ocaml - Camlp5(原Camlp4)如何解析表达式

f# - OCaml、F# 连续、级联 let 绑定(bind)

ocaml - 如何在 Core.Std 中查找文档?

ocaml - 我应该如何在 ocaml 顶层清除屏幕?

types - 用于类型推断的 OCaml LET REC 键入规则

arrays - OCaml - 将 csv 文件读入数组

functional-programming - "Break"在 OCaml 中不合时宜?

dictionary - 如何在 Reason ML 中声明 map 类型?