DEV Community

Oumayma JavaScript Developer
Oumayma JavaScript Developer

Posted on • Updated on

Elixir: Repeating the same function multiple times in pipe

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()))))
Enter fullscreen mode Exit fullscreen mode

Piping allow us to do this:

other_function() |> new_function() |> baz() |> bar() |> foo()
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

usage:

my_struct |> validate_lengths(fields)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)