4

In C++ I'd write

bool positive (int a)
{
#ifdef DEBUG
    cout << "Checking the number " << a << "\n";
#endif
    return a > 0;
}

In OCaml I could write

let positive x = 
    begin
        printf "Checking the number %d\n" x;
        x > 0
    end 

But how can I disable the printf statement when not in debug mode?

marmistrz
  • 5,974
  • 10
  • 42
  • 94

2 Answers2

4

Without preprocessing you can simply have a global flag defined as let debug = true and write:

if debug then
  printf ...;

This code is removed by ocamlopt if debug is false. That said, it's cumbersome and should be used only where performance of the production code is critical.

Another, less optimized, option is to have a mutable flag. This is more convenient as you don't have to rebuild the program to activate or deactivate debug logging. You would use a command-line option to control this (see the documentation for the Arg module).

let debug = ref false

...

if !debug (* i.e. debug's value is true *) then
  printf ...;
Martin Jambon
  • 4,629
  • 2
  • 22
  • 28
3

you can use cppo : https://github.com/mjambon/cppo. This is available via opam, and offers C like preprocessor features.

Pierre G.
  • 4,346
  • 1
  • 12
  • 25