Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

toString() equivalent in OCaml

Tags:

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?

like image 554
Soham Chakraborty Avatar asked Nov 20 '13 17:11

Soham Chakraborty


1 Answers

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.

like image 61
aneccodeal Avatar answered Sep 17 '22 19:09

aneccodeal