is there an equivalent to (C++) istream::putback(char) for ocaml?
How could I add a character to the beginning of stdin?
is there an equivalent to (C++) istream::putback(char) for ocaml?
How could I add a character to the beginning of stdin?
You cannot do it with an in_channel
or with Stream.t
. Here are some suggestions:
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.
You might have some luck writing a C-Interface to that function directly. I can see this being a really bad idea.
Have you considered using an accumulator instead?
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.
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.
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.