Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to print user-defined datatypes in ocaml?

Tags:

ocaml

I can't use print_endline because it requires a string, and I don't (think) I have any way to convert my very simple user-defined datatypes to strings. How can I check the values of variables of these datatypes?

like image 571
tessr Avatar asked Sep 22 '11 17:09

tessr


People also ask

What is :: In OCaml?

The ' is simply part of the variable name. And yes foo :: bar , where foo is an element of type a and bar is a list of type a, means "the list that has foo as its first element, followed by the elements of bar". So the meaning of the match statement is: If xs is the empty list, the value is 0.

How do I print a new line in OCaml?

OCaml has built-in printing functions for a few of the built-in primitive types: print_char , print_string , print_int , and print_float . There's also a print_endline function, which is like print_string , but also outputs a newline.

What is a constructor in OCaml?

The individual names of the values of a variant are called constructors in OCaml. In the example above, the constructors are Sun , Mon , etc.


1 Answers

In many cases, it's not hard to write your own string_of_ conversion routine. That's a simple alternative that doesn't require any extra libraries or non-standard OCaml extensions. For the courses I teach that use OCaml, this is often the simplest mechanism for students.

(It would be nice if there were support for a generic conversion to strings though; perhaps the OCaml deriving stuff will catch on.)

like image 66
stevez Avatar answered Sep 23 '22 13:09

stevez