Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
[Caml-list] selective printf-like function
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Pierre Weis <pierre.weis@i...>
Subject: Re: [Caml-list] selective printf-like function
> >I'd like to write a function that will optionally print something.  It
> >seems simple, but I also want it to be able to take format strings and act
> >like printf.  So for example,
> There was a thread on a related topic just last week.  Search the archives.
> Chris

Right, but the answer was using Obj.magic, which is not only useless
but also harmful to recommand to a beginner (once more, you must
consider that you need a correctness proof to use Obj.magic!).

So, here is a simpler solution only using regular functional

open Printf;;

let debug = ref false;;

let dprintf fmt =
 if !debug then kprintf (fun s -> print_string s; "") fmt
 else kprintf (fun s -> "") fmt;;
val dprintf : ('a, unit, string) format -> 'a = <fun>

The only problem is that dprintf returns a string instead of returning
a unit value as we would like it to do. This is due to the type of the
first argument to kprintf (string -> string). It will be improved in
the next release of Caml, thanks to the better typing of kprintf (the
first argument of kprintf now can have the more general type string ->

In the next release, you thus will prefer to write simply:

let dprintf fmt =
 if !debug then kprintf print_string fmt else kprintf ignore fmt;;

Anyhow, the preceding version will still be accepted by the new
compiler, so that your code will not be broken.

Hope this helps,

Pierre Weis

INRIA, Projet Cristal,,

To unsubscribe, mail Archives:
Bug reports: FAQ:
Beginner's list: