Ocaml Print Statements

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?

0

3 Answers

You will be fine if you embed the print in an expression sequence.

UPDATE

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

# let fac n =
  let rec f i n acc =
    if i >= n
    then acc
    else (Printf.printf "%8d%8d%8d\n" i n 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 the print, but the result still turned out to be 120 as expected.

2

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.

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");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.