DEV Community

Oumayma JavaScript Developer
Oumayma JavaScript Developer

Posted on • Edited on

1

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay