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?
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.
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.
The individual names of the values of a variant are called constructors in OCaml. In the example above, the constructors are Sun , Mon , etc.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With