Capture operator &
ampersand - can always I thing about it as fn x
?
Hi Everybody,
Could you please help me understand how does capture operator &
(ampersand) work under the hood (Elixir or Erlang)?
I went through the whole https://elixir-lang.org/getting-started/introduction.html and one thing I struggled with was the capture operator. Especially when I looked at things like fun = &*/2
which looked like a dark magic till I realized that *
is a function in Kernel
module.
Later I realized that I can rewrite any use of &
from for example &something/1
to &something(&1)
and then to fn x -> something(x) end
.
fn x ->
makes more sense to me so it’s nice to mentally translate &
to fn x ->
. BUT, can I always do that?
I’d like to kindly ask, are &something/1
, &something(&1)
and fn x -> something(x) end
the same thing under the hood of Elixir/Erlang? May I always look at cryptic &something/1
and say that this is just abbreviation of fn x -> something(x) end
?
Thank you.
P.S. my understanding that following Enum.filter are the same thing under the hood.
defmodule SomeMath do
def small_number?(number) do
number >= 0 and number < 10
end
end
IO.puts("let's play")
my_list = [-10, -5, 0, 3, 8, 20, 30]
my_list
|> Enum.filter(fn x -> SomeMath.small_number?(x) end)
|> IO.inspect()
# [0, 3, 8]
my_list
|> Enum.filter(&SomeMath.small_number?(&1))
|> IO.inspect()
# [0, 3, 8]
my_list
|> Enum.filter(&SomeMath.small_number?/1)
|> IO.inspect()
# [0, 3, 8]