List Info

Thread: Re: "ocaml_beginners"::[] Turning a file into a space-delimited stream?




Re: "ocaml_beginners"::[] Turning a file into a space-delimited stream?
user name
2007-01-28 17:43:53

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">maccs.duke.edu

[Non-text portions of this message have been removed]

__._,_.___
.

__,_._,___
Re: "ocaml_beginners"::[] Turning a file into a space-delimited stream?
user name
2007-01-28 17:51:41

On Sun, 28 Jan 2007, Mac Mason wrote:

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

Good to know. Thanks for reporting back, Mac.

Dave

__._,_.___
.

__,_._,___
[1-2]

about | contact  Other archives ( Real Estate discussion Medical topics )