4

As I understand it, because of the design and underlying philosophy of OCaml, there is no general-purpose printing function that can be used, for example, to print out arbitrary data structures such as, for example, this one

[([2; 1; 0], 1.); ([2; 1], 0.471206873564138595); ([2; 0], 0.467882609464025379)]

for debugging purposes. A function that could handle every data structure would have no input type in OCaml, which doesn't make any sense.

I can write a little function to print any data structure I can make from standard data structures--lists, tuples, numbers, etc. (as illustrated here and here) and then I have to write another little function for a different data structure, and so on. That's a lot of work if you just want to get some debugging output.

However, utop and ocaml use a built in pretty-printing routine in order to display evaluation results of any type, and display the contents of lists, tuples, etc. Is there a way to get access to this function--i.e. to get access to the P part of the REPL? In fact, I did a mouse copy from utop's terminal output to construct the string that I used to display a list above. Can't I do that from my code?

I accept that if it's possible to do this, it would in fact be a Bad Thing to do in general, and that it should only be used for debugging and other simple purposes. To use a general-purpose printing function widely would be to thwart the type system that is one of the reasons to use OCaml in the first place.

(I'm sure the answer is "No, you can't do that", or I would have come across a way to do it. Why, though? Seems simple enough.)

Community
  • 1
  • 1
Mars
  • 8,689
  • 2
  • 42
  • 70

1 Answers1

2

The print functions of the toplevel and utop have access to type information. An ordinary OCaml executable (bytecode or native) has no type information (to speak of). So you can't just plug in the print function from the toplevel or utop.

This is a fairly commonly asked question (because it would indeed be handy for debugging). There's a little more information in this previous SO answer: How can OCaml values be printed outside the toplevel?

Community
  • 1
  • 1
Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108
  • Thanks. That makes sense now. I'd looked for a similar question in SO, but failed to find it, though I knew that others had wondered the same thing. Seems like my question should be marked as a duplicate of the question you linked, and so I've voted to close my own question. I don't know if that makes sense. – Mars May 08 '17 at 06:26