nikiiv
Why I can't use anon functions in pipes
I am learning Elixir and I wonder why I can’t use anon function in a pipe but must use the then macro
For example this works
“Hello” |> String.reverse |> String.upcase |> then(&(“Weird text #{&1}”))
But of course this does not
“Hello” |> String.reverse |> String.upcase |> &(“Weird text #{&1}”)
Even in a module I need to access the function with the module prefix
defmodule Test do
def fx(x) do
"Weird Text #{x}"
end
def try(str) do
str
|> String.upcase
|> String.reverse
|> Test.fx #<--- this line
end
end
If i don’t use fx it doesn’t 'compile"
Marked As Solved
Marcus
From the Elixir documentation for left |> right
The second limitation is that Elixir always pipes to a function call. Therefore, to pipe into an anonymous function, you need to invoke it:
some_fun = &Regex.replace(~r/l/, &1, "L")
"Hello" |> some_fun.()
Alternatively, you can use
then/2for the same effect:
some_fun = &Regex.replace(~r/l/, &1, "L")
"Hello" |> then(some_fun)
Your first example would looks like
"Hello" |> String.reverse |> String.upcase |> (&("Weird text #{&1}")).()
You module should work with that changes:
defmodule Test do
def fx(x) do
"Weird Text #{x}"
end
def try(str) do
str
|> String.upcase()
|> String.reverse()
|> fx()
end
end
Also Liked
hst337
No, you don’t. Perhaps you have some other error
nikiiv
Thank you…,







