Pipelining Your Functions
Learn how to use Elixir's pipe operator to combine functions.
We'll cover the following...
Elixir has the famous pipe operator used for combining functions to achieve a greater goal. It has a helpful syntax to execute many functions in sequence, and it’s easy to read and understand. Other functional languages have a higher-order function that can compose functions. Elixir doesn’t have a built-in function or an operator for function composition, but we can create it by using the pipe operator to combine two functions.
Function composition and the pipe operator are useful for creating maintainable code by combining many small and focused routines. Let’s see them in action, and we’ll understand why we should prefer the pipe operator.
First, let’s create a function that composes functions in a HighOrderFunctions
module.
defmodule HigherOrderFunctions do def compose(f, g) do fn arg -> f.(g.(arg)) end end end
The function compose/2
receives two functions and builds a new one that accepts one argument. The function executes the g
function with the given argument and calls f
with the result. This function permits wrapping two function calls in one. We can use it like this:
$iex
iex> c("higher_order_functions.ex")
iex>
...