Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] kprintf with user formatters
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Damien <Damien.Pous@e...>
Subject: Re: [Caml-list] kprintf with user formatters
your CPS solution is fine (except its syntax), 
but I would like to defend my solution...

On Fri, 16 Jul 2004 08:02:27 +0200 (MET DST) Pierre Weis wrote:
> # let log b fmt = 
>     if b then Printf.printf fmt else 
>     let rec f x = Obj.magic f in f fmt;;
> val log : bool -> ('a, out_channel, unit) format -> 'a = <fun>
> # let x = log false "";;
> val x : unit = <unknown constructor>
> # Marshal.to_string x [];;
> Exception: Invalid_argument "output_value: abstract value (outside
> heap)".
> 
> There is clearly something wrong!
then, what about the following :-)
# Marshal.to_string (fun () -> ()) [];;
Exception: Invalid_argument "output_value: abstract value".

> It is overkill to introduce a new printf function just for that case.
maybe...
but it is not to hard to implement (after a quick look at printf.ml)
without the "invalid unit value" problem:

<<
let count fmt = 
  (* this function could be implemented more safely using Printf
     internals*)  
  let s = string_of_format fmt in
  let rec aux a i = 
    match String.unsafe_get s i with
      | '%'  ->
	  (match String.unsafe_get s (i+1) with
	     | '%'  -> aux a (i+2)
	     | '!'  -> aux a (i+2)
	     | 'a'  -> aux (a+2) (i+2)
	     | _    -> aux (a+1) (i+2))
      | '\000'   -> a
      | _    -> aux a (i+1)
  in aux 0 0

let rec eat = function
  | 0 -> Obj.magic ()
  | i -> Obj.magic (fun x -> eat (i-1))

let zprintf (fmt: ('a, _, _, _) format4): 'a = eat (count fmt)

let log b = if b then Printf.printf else zprintf
>>

if (like me), you don't like Obj.magic, please have look at printf.ml...

regards,
damien

-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners