Héctor
Héctor

Reputation: 26034

Passing a function to Enum.map in Elixir

I'm learning Elixir and I wonder if there is a better way to pass a function pointer to Enum.map. I have this code:

defmodule MyModule do

    defp greet(person) do
        IO.puts "Hello " <> person
    end

    def main() do
        people = ["Manuel Bartual", "El hijo de la Tomasa"]
        Enum.map(people, &greet/1)
    end

end

It works fine, but I wonder if there is another way to do this instead of using &greet/1

Upvotes: 1

Views: 2582

Answers (1)

moveson
moveson

Reputation: 5213

More idiomatic would be:

def main do
  ["Manuel Bartual", "El hijo de la Tomasa"]
  |> Enum.map(&greet/1)
end
  1. You should not use parentheses when no arguments are required in the function.

  2. The pipeline operator (|>) is one of the most idiomatic Elixir features. It says, take the result that was just evaluated and call the following function passing that result as the first argument.

Upvotes: 8

Related Questions