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?
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.
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.
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