From 71ed17387cab3f137bc2390c16ad25e32687e56a Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 3 Jul 2018 11:53:01 -0500 Subject: [PATCH] Add Create A Stream From An Array as a reasonml til --- README.md | 3 ++- reason/create-a-stream-from-an-array.md | 35 +++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 reason/create-a-stream-from-an-array.md diff --git a/README.md b/README.md index 4dc108c..a97a5b7 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/). -_685 TILs and counting..._ +_686 TILs and counting..._ --- @@ -502,6 +502,7 @@ _685 TILs and counting..._ ### ReasonML - [Break Out Of A While Loop](reason/break-out-of-a-while-loop.md) +- [Create A Stream From An Array](reason/create-a-stream-from-an-array.md) - [Defining Variants With Constructor Arguments](reason/defining-variants-with-constructor-arguments.md) - [Dynamically Create A Printf String Format](reason/dynamically-create-a-printf-string-format.md) - [Exhaustive Pattern Matching Of List Variants](reason/exhaustive-pattern-matching-of-list-variants.md) diff --git a/reason/create-a-stream-from-an-array.md b/reason/create-a-stream-from-an-array.md new file mode 100644 index 0000000..2dcb0bb --- /dev/null +++ b/reason/create-a-stream-from-an-array.md @@ -0,0 +1,35 @@ +# Create A Stream From An Array + +There are functions in the [`Stream` +module](https://reasonml.github.io/api/Stream.html) for turning a variety of +data structures into streams -- lists, input channels, etc. + +What if you have an array? + +The `Stream.from` function lets you define a function for custom fitting +data structures into streams. Let's take a look: + +```reason +let pokemon = [| "bulbasaur", "charmander", "squirtle" |]; + +let poke_stream: Stream.t(string) = + Stream.from(i => + switch (pokemon[i]) { + | pokemon => Some(pokemon) + | exception (Invalid_argument("index out of bounds")) => None + } + ); +``` + +The function takes the current index and needs to either return `Some('a)` +with the corresponding value or `None` if the stream is empty. + +With that, we now have a stream on which we can invoke any of the stream +functions. + +```reason +switch (Stream.next(poke_stream)) { +| pokemon => print_endline(Printf.sprintf("Next Pokemon: %s", pokemon)) +| exception Stream.Failure => print_endline("No pokemon left") +}; +```