Version française
Home     About     Download     Resources     Contact us    
Browse thread
class and printf
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Virgile Prevosto <virgile.prevosto@m...>
Subject: Re: [Caml-list] class and printf
Hello,
Le lun 30 oct 2006 14:47:06 CET,
"Nicolas Pouillard" <nicolas.pouillard@inria.fr> a écrit :

> On 10/30/06, Anastasia Gornostaeva <ermine@ermine.pp.ru> wrote:
> > Hello.
> >
> > What I need to drink to compile it?
> >
> > class foo ch =
> > object
> >  method myprintf = Printf.fprintf ch
> > end
> This one works:
> 
> class ['a] foo ch =
> object
>  method myprintf (fmt : ('a, out_channel, unit) format) =
>    Printf.fprintf ch fmt
> end
> 

While this solution compiles fine, there might an issue with it,
depending on the context where it is to be used: an instance of foo
won't be really polymorphic, so that you'll have to use it with 
the same kind of format string everywhere (from another point of
view, it means that you must define an instance for "%s", one for "%d",
etc.):

# let  bar = new foo stdout;;
val bar : '_a foo = <obj>
# bar#myprintf "foo\n" (* fixes the kind of format string bar
                            can handle *);;
* foo
- : unit = ()
# bar#myprintf "%s" "foo";;
Characters 0-12:
  bar#myprintf "%s" "foo";;
  ^^^^^^^^^^^^
This function is applied to too many arguments,
maybe you forgot a `;'
# bar;; (* check that '_a has been unified with unit *)
- : unit foo = <obj>

Maybe a polymorphic method would be better here:

class foo ch =
object
 method myprintf : 'a.('a, out_channel, unit) format -> 'a =
   fun fmt -> Printf.fprintf ch fmt
end
;;
            class foo :
  out_channel ->
  object method myprintf : ('a, out_channel, unit) format -> 'a end
# let bar = new foo stdout;;

val bar : foo = <obj>
#   bar#myprintf "foo\n";;

foo
- : unit = ()
#   bar#myprintf "%s" "foo";;

foo- : unit = ()


-- 
E tutto per oggi, a la prossima volta.
Virgile