Piping is a trade mark for elixir developers, it makes the code cleaner, easier to read and overall more organized.
Instead of chaining function returns like this:
foo(bar(baz(new_function(other_function()))))
Piping allow us to do this:
other_function() |> new_function() |> baz() |> bar() |> foo()
Where the data flows from up to bottom.
Sometimes on our programming journey we need to perform the same function n times while piping.
1. Performing the same function on enum items inside a pipe:
We have Enum of strings that we want to transform to uppercase.
people = ["Qui", "Quo", "Qua"]
people|> Enum.map(&String.upcase/1)
2. Piping the same function multiple times on the same variable.
For example let's say we have a struct that we want to validate the fields.
In this case we can simplify the piping using a function
def validate_lengths(changeset, fields, opts) do
Enum.reduce(fields, changeset, &validate_length(&1, &2, opts))
end
usage:
my_struct |> validate_lengths(fields)
Top comments (0)