Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] How to read three integers from a text-file... ?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: John Prevost <visigoth@c...>
Subject: Re: [Caml-list] How to read three integers from a text-file... ?
>>>>> "ch" == Chris Hecker <checker@d6.com> writes:

    ch> As Markus says, the Printf.printf doesn't work in this case
    ch> anyway right now, since it happens completely at compile time,
    ch> I believe.

Actually, this is not the case, though printf formats are limited in
what you can do with them.  (i.e. you may substitute, but not
combine.)

As an example:

# let fmt x = (x : ('a,'b,'c) format)

  let a = fmt "First: %d, Second: %d\n"
  let b = fmt "[1, %d; 2, %d]\n"
  let f fmt = Printf.printf fmt 10 10
  let _ = f a
  let _ = f b
  ;;

First: 10, Second: 10
[1, 10; 2, 10]
val fmt : ('a, 'b, 'c) format -> ('a, 'b, 'c) format = <fun>
val a : (int -> int -> unit, out_channel, unit) format = <abstr>
val b : (int -> int -> unit, out_channel, unit) format = <abstr>
val f : (int -> int -> 'a, out_channel, unit) format -> 'a = <fun>

The definition of fmt is just to provide a quick way to force a string
into the context of a format type--otherwise, the cimpiler would
assign the type string to that value.

So it is possible to do some small things with these formats.  A more
interesting strategy is to use formatting combinators:

let id x = x
let ( ** ) f g x = f (g x)

let str     k s x = k (s ^ x)
let int     k s x = k (s ^ string_of_int x)
let lit p x k s   = p k s x

let lis p   k s x = match x with
  | [] -> k (s ^ "[]")
  | _  ->
    let rec loop xs k s = match xs with
      | [x]   -> p (fun s -> k (s ^ "]")) s x
      | x::xs -> p (fun s -> loop xs k (s ^ ";")) s x
    in loop x k (s ^ "[")

let format p = p id ""

Which lets you do things like:

# format (int ** lit int 3) 5;;
- : string = "53"
# format (int ** lit str " -> " ** lis int) 5 [1;2;3;4;5];;
- : string = "5 -> [1;2;3;4;5]"

Of course, these combinators can be extended for other ways of
producing results, and you can add new formats later.  So, it's more
extensible than the current printf is.  Quite nice, really.

John.
-------------------
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