2013-11-20 114 views
9

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

+0

它一直OCaml中的一个致命英尺。答案可能取决于您使用* Core *还是* Batteries *。 – lukstafi

回答

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

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

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

+2

Sexplib库也可能有用。 – Kakadu

4

如果你使用Core和相关的Sexplib语法扩展,这里有很好的解决方案。从本质上讲,sexplib自动从OCaml类型向s表达式转换和从s表达式转换,提供了一种方便的序列化格式。

下面是使用Core和Utop的示例。请务必按照以下说明为让自己设置为使用核心: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