Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] Printf.sprintf ?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Brian Rogoff <bpr@b...>
Subject: Re: [Caml-list] Printf.sprintf ?
On 15 Aug 2001, Johann Spies wrote:

> Can somebody please explain this to me:
> 
> This works as expected:
> 
> # let s = Printf.sprintf "%s" "enigiets";;
> val s : string = "enigiets"
> 
> But this not:
> 
> # let q = "%s";;
> val q : string = "%s"
> # let s = Printf.sprintf q "enigiets";;
> Characters 23-24:
> This expression has type string but is here used with type
>   (string -> 'a, unit, string) format
> 
> Why?

Because Printf is a bit of a hack, in that the syntax for a format string
is the same as the syntax for a regular string. As a beginner, when you
use Printf, it's easier to use the format string as a literal and not
as a variable. If you feel you must do this, the polite way is as follows 

# let q = ("%s" : ('a, 'b, 'c) format);;  
val q : (string -> 'a, 'b, 'a) format = <abstr>
# let s = Printf.sprintf q "enigiets";;
val s : string = "enigiets"

and there's also a rude way (forgive me Berke! :) 

  let s : string = Printf.sprintf (Obj.magic q) "enigiets";;

-- Brian

(*) Yes, I'm a C programmer too so it's a welcome hack. 

-------------------
Bug reports: http://caml.inria.fr/bin/caml-bugs  FAQ: http://caml.inria.fr/FAQ/
To unsubscribe, mail caml-list-request@inria.fr  Archives: http://caml.inria.fr