views:

251

answers:

3

is there an equivalent to (C++) istream::putback(char) for ocaml?

How could I add a character to the beginning of stdin?

+3  A: 

You cannot do it with an in_channel or with Stream.t. Here are some suggestions:

  1. If you are putting back a character you had read, you might want to use use peek to examine the stream instead of removing the element.

  2. You might have some luck writing a C-Interface to that function directly. I can see this being a really bad idea.

  3. Have you considered using an accumulator instead?

  4. Write a module around the current functions with a type that is a zipper or stack or some other structure that allows pushing characters back.

nlucaroni
+1  A: 

OCaml Batteries Included features a much more comprehensive and much higher-level interface for streams. You could take a look at this. Plus, generally, it's good.

Yoric
Batteries is good, but it doesn't (directly) support this functionality with its IO streams.
Michael E
Indeed, but the IO abstraction doesn't prevent it, by opposition to the IO abstraction in the OCaml standard library. So it can be added, which is better than nothing.
Yoric
+1  A: 

Basically: you can't. Batteries (and Extlib) provide an enhanced I/O wrapper, but neither of them support this function.

You can, however, emulate it with either Batteries or Extlib if you are willing to do only character-level reads, bu wrapping the I/O stream in an Enum (BatEnum with Batteries). Enum provides a general enumeration with a "get next value" type of interface, and allows you to push values back on to the front of the enum. So you can wrap stdin in an enum of type char Enum.t which returns characters with its Enum.next function, and then use Enum.push to push the unwanted characters back on to the front of it.

It may be possible then to re-wrap such an enum with IO (BatIO) for a more flexible interface, if you first verified that those modules don't perform internal buffering that would mess up the semantics of pushing characters.

Michael E