Mix.install([
{:youtube, github: "brooklinjazz/youtube"},
{:hidden_cell, github: "brooklinjazz/hidden_cell"},
{:tested_cell, github: "brooklinjazz/tested_cell"},
{:utils, path: "#{__DIR__}/../utils"}
])
Ensure you type the ea
keyboard shortcut to evaluate all Elixir cells before starting. Alternatively, you can evaluate the Elixir cells as you read.
To create more complex behavior, you'll often compose smaller functions together. Composing functions together reflects nature of problem-solving where we take large problems and break them down into smaller ones.
To help compose functions together, Elixir provides the pipe |>
operator.
That's the |
symbol likely above your enter key, and the greater than >
symbol side by side to make |>
.
The pipe operator allows you to take the output of one function and pass it in as an argument for the input of another function.
flowchart LR
A[Input] --> B[Function1]
B --> C[Pipe]
C --> D[Function2]
D --> E[Output]
Why is this useful? Without the pipe operator you can wind up writing deeply nested function calls.
four.(three.(two.(one.())))
But with the pipe operator, you can chain functions together.
one.() |> two.() |> three.() |> four.()
If a function is called with multiple arguments, the function piped in will be the first argument.
two(1, 2) # how to call two/2 by itself.
# How to use the pipe operator
# to call the two/2 with one/1 as the first argument.
one.() |> two.(2)
You can also pass in a value to a pipe.
1 |> two.()
The pipe operator doesn't change the behavior of a program. Instead, the pipe operator exists as syntax sugar to improve the clarity of your code.
add_grapes = fn shopping_list -> shopping_list ++ ["grapes"] end
add_pizza = fn shopping_list -> shopping_list ++ ["pizza"] end
add_blueberries = fn shopping_list -> shopping_list ++ ["blueberries"] end
[]
|> add_grapes.()
|> add_pizza.()
|> add_blueberries.()
|> add_pizza.()
|> add_blueberries.()
# vs the alternative
add_blueberries.(add_pizza.(add_blueberries.(add_pizza.(add_grapes.([])))))
Run the following in your command line from the beta_curriculum folder to track and save your progress in a Git commit.
$ git add .
$ git commit -m "finish pipe operator section"