Skip to content

Commit 383c927

Browse files
committed
Brief description of the pipe operator in chapter 10
I added a brief description of the pipe operator (`|>`) in chapter 10, when it is first used. This has been suggested by @josevalim in elixir-lang#395.
1 parent f099a14 commit 383c927

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

getting_started/10.markdown

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,18 +54,28 @@ iex> 1..100_000 |> Enum.map(&(&1 * 3)) |> Enum.filter(odd?) |> Enum.sum
5454

5555
The example above has a pipeline of operations. We start with a range and then multiply each element in the range by 3. This first operation will now create and return a list with `100_000` items. Then we keep all odd elements from the list, generating a new list, now with `50_000` items, and then we sum all entries.
5656

57-
As an alternative, Elixir provides [the `Stream` module](/docs/stable/elixir/Stream.html) which supports lazy operations:
57+
### 10.2.1 The pipe operator
58+
59+
The `|>` symbol used in the snippet above is the **pipe operator**: it simply takes the output from the expression on its left side and passes it as the input to the function call on its right side. It's similar to the Unix `|` operator. Its purpose is to highlight the flow of data being transformed by a series of functions. To see how it can make the code cleaner, have a look at the example above rewritten without using the `|>` operator:
5860

5961
```iex
60-
iex> 1..100_000 |> Stream.map(&(&1 * 3)) |> Stream.filter(odd?) |> Enum.sum
62+
iex> Enum.sum(Enum.filter(Enum.map(1..100_000, &(&1 * 3)), odd?))
6163
7500000000
6264
```
6365

64-
Instead of generating intermediate lists, streams create a series of computations that are invoked only when we pass it to the `Enum` module. Streams are useful when working with large, *possibly infinite*, collections.
66+
Find more about the pipe operator [by reading its documentation](http://elixir-lang.org/docs/stable/elixir/Kernel.html#|>/2).
6567

6668
## 10.3 Streams
6769

70+
As an alternative to `Enum`, Elixir provides [the `Stream` module](/docs/stable/elixir/Stream.html) which supports lazy operations:
71+
72+
```iex
73+
iex> 1..100_000 |> Stream.map(&(&1 * 3)) |> Stream.filter(odd?) |> Enum.sum
74+
7500000000
75+
```
76+
6877
Streams are lazy, composable enumerables.
78+
Instead of generating intermediate lists, streams create a series of computations that are invoked only when we pass it to the `Enum` module. Streams are useful when working with large, *possibly infinite*, collections.
6979

7080
They are lazy because, as shown in the example above, `1..100_000 |> Stream.map(&(&1 * 3))` returns a data type, an actual stream, that represents the `map` computation over the range `1..100_000`:
7181

0 commit comments

Comments
 (0)