Stream A File Line By Line
We can use the Stream
module in ReasonML to read a file getting each line on demand. Doing this requires two key insights. First, we can open a file as an input channel. Second, we can turn an input channel into a stream using Stream.from
.
The Pervasives
module (which is open by default and is only prefixed above so as to be explicit) allow us to open the named file as an input channel with open_in
. It also allows us to read lines off that file with input_line
. We use Stream.from
to create a custom stream that consumes the input channel line by line using input_line
. We either get some line or we hit the end of the file. Lastly, we can do whatever we want with the stream, such as iterate over it.
See the docs for Pervasives
and Stream
for more details.
Last updated