The developer experience of the |> pipe operator in Elixir
My first experience with |>
(the pipe operator) in Elixir was that I didn’t know what it was called and didn’t know how to google for it. I started with “vertical bar greater than elixir” and eventually stumbled my way to it.
The experience of using the pipe operate was called “chef’s kiss” by someone I talked to and I tend to agree.
One of my very literal shower thoughts was that for SVO languages like English, the pipe operator seems to allow more natural comprehension.
SVO comes from linguistics and stands for Subject Verb Object and reflects the normal word order a language tends to take. Take “Bob ate veggies” and in an SOV language like Japanese, would be structured like “Bob veggies ate”.
In programming usually the verb comes first:
print(“something”)
And often, the object follows the subject:
parse_integer(some_number_string, base10)
Object-oriented languages sometimes can adopt an SVO like syntax:
dog = MakeAnimal()
dog.bark("mailman")
But usually programming is verb first. Functions are central to how we read code.
The Pipe operator allows us to model code in an SVO manner:
list
|> map(fn v -> v+1 end)
This “reads” conceptually like: The List will map over every value, adding one to each.
map_of_user_info
|> Map.put(:zipcode, 90210)
|> Map.delete(:postal_code)
Similarly this “reads” like The list will add a zipcode key-value and delete the postal_code key-value.
The chaining allows you to focus on the verbs without having intermediate nouns.
list_of_degrees_in_c
|> map(fn v -> v*9/5 + 32 end)
|> average()
|> is_too_hot?()
It’s the linguistic equivalent of:
Take the list of temperatures, convert them to F, get the average and check if it’s too hot.
and for comparison, with intermediate nouns:
list_of_degrees_in_f = map(list_of_degrees_in_c, fn v -> v*9/5 + 32 end)
avaerage_temp_in_f = average(list_of_degrees_in_f)
is_too_hot_this_month = is_too_hot?(avaerage_temp_in_f)
Take the list of temperatures and convert them to F. Take the list of temperatures in F and get the average. Take the average temperature and check if it’s too hot.
After fairly quick acclimation period, the pipe operator has become one of my favorite parts of Elixir.
I don’t throw around words like blissful lightly. Having a log chain of pipe is honestly delightful. It’s like watching your own conceptual Rube Goldberg machine but in a good way.
Chef’s Kiss indeed.
bonus promotional message:
My startup is hiring a backend engineer in the SF Bay Area. Our tech stack is nearly all implemented in Elixir/Phoenix/LiveView.