Reputation: 22170
I just wrote:
def transform(list_of_functions, elem) do
Enum.reduce(list_of_functions, elem, fn func, res when is_function(func) -> func.(res) end)
end
To be called like:
transform([
&(2*&1),
fn x -> x % 3 end,
&Integer.to_string/1
], 5) # "1"
But it feels so elementary that I'm wondering if such function exists in Elixir itself. I would have expected Enum.transform/2
but it doesn't exist. :( Does it with another name?
Upvotes: 0
Views: 410
Reputation: 121000
This is counter-idiomatic in elixir. We usually use pipe operator |>
for that.
Sidenote: %
is not an operator to perform modulo division, btw, rem/2
is.
5
|> Kernel.*(2)
|> rem(3)
|> Integer.to_string()
#⇒ "1"
Of course, if needed, that might be written in foldl
notation.
Enum.reduce([
&(2*&1),
&rem(&1, 3),
&Integer.to_string/1
], 5, & &2 |> &1.())
#⇒ "1"
But still, elixir is not haskell, carrying functions is not how idiomatic code is being written.
Upvotes: 4