Part Six | Functional Programming Through Elixir: The Pipe Operator
Unreadable Nesting
In Part Five, we saw how recursion replaces loops. Now let’s look at a different readability problem: nested function calls.
Say you need to take a user’s input, trim whitespace, convert it to lowercase, and capitalize the first letter. In Elixir, without the pipe operator, you’d write:
String.capitalize(String.downcase(String.trim(" HELLO WORLD ")))
# "Hello world"You have to read this from the inside out. The first operation (trim) is buried in the middle, and the last operation (capitalize) is on the outside. The more steps you add, the worse it gets.
If you’re coming from OOP, you might be used to method chaining, which reads left to right:
# Python - method chaining
" HELLO WORLD ".strip().lower().capitalize()
# "Hello world"// JavaScript - method chaining
" HELLO WORLD ".trim().toLowerCase()
// "hello world"
// (JavaScript doesn't have a direct capitalize method)
Method chaining reads nicely, but it only works because each method is attached to the object. In functional programming, functions aren’t bound to objects. They’re standalone. So how do we get the same readability?