OCaml Printing Operations

Can I put print instructions for debugging / testing in code blocks? For example, in Java, you can use System.out.println("") in the middle of methods to check for variables or other things, but will a command like print_string work in OCaml? Will the value of the unit of type return, which will lead to an error, instead of allowing you to print it?

+13
source share
3 answers

Everything will be fine if you embed printing in a sequence of expressions .

UPDATE

Here is a concrete example, because the answer above was rather short and, well, answers with only links are not good answers. This is a classic tail recursive factorial formulation (yes, boring, but familiar):

 # let fac n = let rec fin acc = if i >= n then acc else (Printf.printf "%8d%8d%8d\n" in acc; f (i+1) n ((i+1)*acc)) in f 0 n 1;; val fac : int -> int = <fun> # fac 5;; 0 5 1 1 5 1 2 5 2 3 5 6 4 5 24 - : int = 120 

Here you can see the side effects of printing, but the result still turned out to be 120, as expected.

+21
source

Since OCaml is not a pure functional language, there are many ways to do this. This is how I write this code, just for a specific example.

 let rec mylength list = (* DEBUG *) let () = Printf.printf "mylength here, null list: %b\n%!" (list = []) in (* DEBUG *) match list with | [] -> 0 | _ :: rest -> 1 + mylength rest 

After that, you can delete the material inside the comments (* DEBUG *).

Pay attention to the use of%! to flush the buffer. If you are debugging a lot with printf (like me), it is very useful to know about this.

+12
source

Here is a simple example that shows that the expression sequences mentioned in the Ray Toal answer do not necessarily require parentheses around them:

 let get_a_string = let a_string = "a string" in (* The semicolon causes the return value of the statement to be discarded *) Printf.printf "Debug: %s\n" a_string; a_string let () = Printf.printf "Result: %s\n" get_a_string 

Another way to reset the return value of a function is to ignore :

 ignore (Printf.printf "Debug info"); 
+4
source

All Articles