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"

1 Like

You can’t because the compiler says so, A programming language is not a natural language.

You can pipe to a closure if it is assigned to a variable

fx = &(“Weird text #{&1}")
str
|> String.upcase()
|> String.reverse()
|> fx.()

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/2 for 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
5 Likes

No, you don’t. Perhaps you have some other error

1 Like

You are correct… I don’t know what was the problem
The first one is the one I am struggling with

Thank you…,

1 Like