Chain Function Calls with the Pipe Operator in Elixir

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 4 years ago

The pipe operator is an easy to use and powerful feature of Elixir. It takes the output from the expression on the left, and automatically passes it as the first argument to the function on the right. This is especially useful when chaining together multiple function calls or data transformations. Using the pipe operator results in code that's easier to read, write and refactor.

Instructor: [00:01] Say, we want to take the string, "Hello World," and run these three transformations on it. We want to reverse it, convert to its uppercase, and then add a bunch of whitespace at the beginning of it.

[00:11] We'll first do this without the pipe operator. Let's run our function each step of the way to see the output. You can see here that we've got "Hello World," but it's been reversed.

[00:28] Next step is to convert to its uppercase. Run it again. We see "Hello World." It's been reversed, and it's uppercased. Finally, let's add the whitespace. We want to add 30 characters of whitespace. Run it one more time. We can see here that we've got whitespace.

[00:53] Our code works, but it's nested and it's difficult to read. If you look at each function call, it's actually reversed from our instructions up here. Let's write this with the pipe operator to see how much easier it becomes to read.

[01:15] First thing we do is we take the value, "Hello World," and we pipe it using this operator into string reverse. You'll notice here that there's no parenthesis on this function call. What's happening is the pipe operator automatically takes this value and passes it as the first argument.

[01:34] Let's run our function, just to make sure. We get "Hello World," but it's been reversed. Now, let's uppercase it. Notice the same pattern emerges. We take the result from this call here and we pipe it into string.upcase.

[01:53] Run it again. "Hello World" reversed and capitalized. Now, finally, let's add the whitespace again. Now, you'll notice that this time, we do pass an argument. This 30 is the same 30 as up here, but this is actually the second argument being passed to pad_leading. The first argument is the result from this call right here.

[02:17] We run the code one more time. We see that we get the same exact result as before. You can see that the code now is much easier to read and the order in which the functions are called matches the directions up here.