The Pipe Operator (|>)

The pipe operator |> is an effective tool in enhancing the readability of your code. Referred to as syntactic sugar, it directs the output from the expression to its left as the first argument into the function on its right. It thus allows for a clean and streamlined way to chain multiple functions together.

It is easier than it sounds. The following code examples explain it.

Consider a case where you wish to reverse a string with String.reverse/1 and subsequently capitalize it using String.capitalize/1. Traditionally, you might go about it as follows:

iex> String.reverse("house") (1)
"esuoh"
iex> String.capitalize("esuoh") (2)
"Esuoh"
iex> String.capitalize(String.reverse("house")) (3)
"Esuoh"
1 String.reverse/1 function reverses the string.
2 String.capitalize/1 function capitalizes the first letter of a string.
3 Both functions are integrated to first reverse and then capitalize the string.

Although String.capitalize(String.reverse("house")) is technically correct, it can be a bit difficult to read. This is where the pipe operator |> comes in handy:

iex> "house" |> String.reverse() |> String.capitalize() (1)
"Esuoh"
1 The pipe operator |> passes the result of the first function as the first parameter to the subsequent function.

Moreover, the pipe operator can be seamlessly chained for multiple operations:

iex> "house" |> String.reverse() |> String.capitalize() |> String.slice(0, 3)
"Esu"

Employing the pipe operator, the code becomes more legible, easier to understand, and more maintainable. The benefits of this operator are particularly noticeable in multi-line source code where each transformation is clearly outlined:

example =
  "house"
  |> String.reverse()
  |> String.capitalize()
  |> String.slice(0, 3)

This presentation enhances clarity and readability of the code, allowing for better understanding and maintenance.