'OCaml Print statements

Is it possible to put print statements for debugging/testing in blocks of code? For example, in Java you can use System.out.println("") in the middle of methods to check variables or other things, but in OCaml, would a command like print_string work? Wouldn't it return a value of type unit, thus causing an error, instead of allowing you to print it?



Solution 1:[1]

Since OCaml isn't a pure functional language, there are many ways to do this. Here is the way I write this kind of code, just for a concrete 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 it works you can remove the stuff inside the (* DEBUG *) comments.

Note the use of %! to flush the buffer. If you do a lot of debugging with printf (as I do), it's really useful to learn about this.

Solution 2:[2]

Here's a simple example that shows that expression sequences as mentioned in Ray Toal's answer don't necessarily need 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 discard a function's return value is using ignore:

ignore (Printf.printf "Debug info");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jeffrey Scofield
Solution 2