On Fri, Jan 26, 2007 at 03:16:17PM -0500, Mac Mason wrote:
> I've got a file that has many, many whitespace-delimited integers (and
> one whitespace-delimited string, as the very first element).
>
> I'm looking for a clean way to read them in one at a time; what I'd
> really like is a stream (or an Enum, I suppose) that's constructed
> from these values. I can put this together as a combination of
> Std.input_all, Str.split, and so on, but it's really awful and I don't
> know much about the tail-recursive properties of those functions (like
> I said: many, many integers). It seems like I should be able to
> (ab)use the stream syntax or module to do this for me.
>
> Thoughts?
>
> Thanks!
Here's my solution, after the things people pointed out.
Thoughts:
* ExtLib's "get the whole file as a string" isn't tail-recursive,
because it blows the stack.
* You need to use Scanf.bscanf, because this hits exactly the bug
described in the fscanf documentation.
let get_pgm_stream filename =
try
let buf = (Scanf.Scanning.from_file filename) in
let rf _ =
try
let nr = Scanf.bscanf buf " %s " (fun x -> x) in
if nr = "" then None else Some nr
with
End_of_file -> None
in
Stream.from rf
with
Sys_error _ -> raise No_such_file
Enjoy!
--Mac
--
Julian "Mac" Mason mac%40cs.duke.edu">mac
cs.duke.edu
[Non-text portions of this message have been removed]
.