From 9527ca8882258b76761bbd10ad827d9bab51fffc Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sun, 22 Jul 2018 20:00:24 -0500 Subject: [PATCH] Add Stream A File Line By Line as a reason til --- README.md | 3 ++- reason/stream-a-file-line-by-line.md | 32 ++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 reason/stream-a-file-line-by-line.md diff --git a/README.md b/README.md index 6af4f76..2fd1432 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_692 TILs and counting..._ +_693 TILs and counting..._ --- @@ -516,6 +516,7 @@ _692 TILs and counting..._ - [Pattern Match On Exceptions](reason/pattern-match-on-exceptions.md) - [Quickly Bootstrap A React App Using Reason](reason/quickly-bootstrap-a-react-app-using-reason.md) - [Seeding And Generating Random Integers](reason/seeding-and-generating-random-integers.md) +- [Stream A File Line By Line](reason/stream-a-file-line-by-line.md) - [String Interpolation With Integers And Sprintf](reason/string-interpolation-with-integers-and-sprintf.md) - [String Interpolation With Quoted Strings](reason/string-interpolation-with-quoted-strings.md) diff --git a/reason/stream-a-file-line-by-line.md b/reason/stream-a-file-line-by-line.md new file mode 100644 index 0000000..4af6d62 --- /dev/null +++ b/reason/stream-a-file-line-by-line.md @@ -0,0 +1,32 @@ +# Stream A File Line By Line + +We can use the `Stream` module in [ReasonML](https://reasonml.github.io/en) +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`. + +```reason +let file_in_channel = Pervasives.open_in('file.txt'); + +let file_stream = + Stream.from(_i => { + switch(Pervasives.input_line(file_in_channel)) { + | line => Some(line) + | exception(End_of_file) => None + }; + }); + +file_stream |> Stream.iter(line => do_something(line)); +``` + +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`](https://reasonml.github.io/api/Pervasives.html) and +[`Stream`](https://reasonml.github.io/api/Stream.html) for more details.