Skip to content

Commit 6740246

Browse files
authored
Simplify streams examples
1 parent db0e336 commit 6740246

File tree

1 file changed

+1
-17
lines changed

1 file changed

+1
-17
lines changed

lib/elixir/pages/getting-started/enumerable-and-streams.md

Lines changed: 1 addition & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -95,26 +95,10 @@ iex> Enum.take(stream, 10)
9595
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1]
9696
```
9797

98-
On the other hand, `Stream.unfold/2` can be used to generate values from a given initial value:
99-
100-
```elixir
101-
iex> stream = Stream.unfold("hełło", &String.next_codepoint/1)
102-
#Function<39.75994740/2 in Stream.unfold/2>
103-
iex> Enum.take(stream, 3)
104-
["h", "e", "ł"]
105-
```
106-
10798
Another interesting function is `Stream.resource/3` which can be used to wrap around resources, guaranteeing they are opened right before enumeration and closed afterwards, even in the case of failures. For example, `File.stream!/1` builds on top of `Stream.resource/3` to stream files:
10899

109100
```elixir
110-
iex> stream = File.stream!("path/to/file")
111-
%File.Stream{
112-
line_or_bytes: :line,
113-
modes: [:raw, :read_ahead, :binary],
114-
path: "path/to/file",
115-
raw: true
116-
}
117-
iex> Enum.take(stream, 10)
101+
iex> "path/to/file" |> File.stream!() |> Enum.take(10)
118102
```
119103

120104
The example above will fetch the first 10 lines of the file you have selected. This means streams can be very useful for handling large files or even slow resources like network resources.

0 commit comments

Comments
 (0)