Pipes in Elixir

Pipes are a delightful feature in Elixir that you can use to pass the evaluation of an expression into a function. For example, the code below will output “Hello, world!” to the terminal:

"Hello, world!"
|> IO.inspect
# "Hello, world!"

You can use this to chain together different operations:

"Hello, world!"
|> String.reverse
|> IO.inspect
# "!dlrow ,olleH"

And Elixir specifically substitutes the result of the expression into the first argument of the following function, so you can still tack arguments onto the end:

"Hello, world!"
|> String.reverse
|> String.upcase
|> IO.inspect(label: "SHOUTING BACKWARDS")
# SHOUTING BACKWARDS: "!DLROW ,OLLEH"

Pipes can help visually represent the path data takes as it flows through your application. At this point, I’m probably using them a bit too much, but it’s just too much fun.

This is cool because in a lot of languages, you can’t represent how your data is processed in such an orderly fashion because you need to adhere to the order that the programming language understands it – inside out. For example, without pipes, the last example would look like this:

IO.inspect(String.upcase(String.reverse("Hello, world!")), label: "SHOUTING BACKWARDS")

Or, with some indentation to make it somewhat easier on the eyes:

IO.inspect(
  String.upcase(
    String.reverse("Hello, world!")
  ),
  label: "SHOUTING BACKWARDS"
)

Typically, a programming language has functions that operate on certain inputs, but, like mathematical functions, those inputs are entered inside the parentheses. If you remember the form f(x) = x + 1 from math class, then you might understand that to solve for g(f(x)), you need to read it backwards in order to evaluate it: first, you must know what x is, then you have to solve f(x) in order to finally solve for g(x). The way programming languages operate is similar, except that it’s the computer that’s doing the solving, or evaluation, of your code. Pipes let you invert that and visually represent it as “first x, then apply f, then g” or x ➡️ f ➡️ g, to use pseudo-code.

Feel free to play with these examples here: https://replit.com/@briankung/Pipes-in-Elixir

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s