Soham Chakraborty
Soham Chakraborty

Reputation: 221

toString() equivalent in OCaml

I am new to OCaml and trying to debug some OCaml code. Is there any function in OCaml equivalent to toString() function in Java by which most of the objects can be printed as output?

Upvotes: 12

Views: 5660

Answers (2)

yzzlr
yzzlr

Reputation: 875

If you use Core and the associated Sexplib syntax extension, there are pretty good solutions to this. Essentially, sexplib auto-generates converters from OCaml types to and from s-expressions, providing a convenient serialization format.

Here's an example using Core and Utop. Make sure you follow the following instructions for getting yourself set up to use 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))))"

You can also generate sexp-converters for un-named types, using the following inline quotation syntax.

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

More detail is available here: https://realworldocaml.org/v1/en/html/data-serialization-with-s-expressions.html

Upvotes: 6

aneccodeal
aneccodeal

Reputation: 8913

There are functions like string_of_int, string_of_float, string_of_bool in the Pervasives module (you don't have to open the Pervasives module because it's... pervasive).

Alternatively, you can use Printf to do this kind of output. For example:

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 

There's also a sprintf function in the Printf module, so if you wanted to just create a string instead of printing to stdout you could replace that last line with:

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

For more complex datatypes of your own definition, you could use the Deriving extension so that you woudn't need to define your own pretty-printer functions for your type.

Upvotes: 11

Related Questions