One neat feature of Elixir is the pipe operator (|>
). The pipe operator lets you avoid awkward code like this:
thirdFunction(secondFunction(firstFunction(x)));
Or this:
const firstResult = firstFunction(x); const secondResult = secondFunction(firstResult); thirdFunction(secondResult);
Instead of having to read in reverse or litter your code with single-use variables, Elixir lets you pipe your function calls together.
first_function(x) |> second_function() |> third_function()
The pipe operator takes the result of the expression to the left and makes it the first argument to the following function call. Functions from the standard library generally have a consistent argument order, which makes them very easy to compose using the pipe operator.
"Here are some words" |> String.upcase() # => "HERE ARE SOME WORDS" |> String.split(" ") # => ["HERE", "ARE", "SOME", "WORDS"] |> Enum.reverse() # => ["WORDS", "SOME", "ARE", "HERE"] |> Enum.filter(&(String.length(&1) == 4)) # => ["SOME", "HERE"] |> List.first() #=> "SOME"
The pipe operator is just one of many things I enjoy about Elixir. It feels very similar to using a fluent interface, but without objects or methods.