benhoven

benhoven

Capture operator `&` ampersand - can always I thing about it as `fn x`?

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]

Most Liked

hauleth

hauleth

And &Module.foo/1 is even more performant, as it can be changed to compile time constant in compiler. That is the reason why it is encouraged way to register telemetry handlers.

11
Post #3
benhoven

benhoven

Thank you very much NobbZ and hauleth. And thank you jawakarD for very detailed answer.

To summarize it:

Mental translations

  • &something/1 / &something(&1) / fn x -> something(x)

  • &something/2 / &something(&1, &2) / fn x, y -> something(x, y)

  • &something(&2, &1) / fn x, y -> something(y, x)

  • &(&1 + &2 * &3 + 199) / fn x, y, z -> x + y * z + 199 end

  • it’s OK to mentally translate

  • under the hood one thing might translate to other and something might be faster than other but from a user (developer) perspective result is the same

Under the hood

order of translation

  • &(...&1...&2...) -> fn x, y -> ... -if possible-> &something/2

performance

  • &something/2 is faster than &(...&1...&2...) / fn x, y -> ... (in case &(...&1...&2...) / fn x, y -> ... cannot be translated to &something/2)

  • That means I should design my CoolApp.something functions so they can be used in things like Enum.reduce as &CoolApp.something/2 and not as &CoolApp.something(&2, &1) / fn x, y -> ...y...x...

best practice

  • I should always ask myself a question if it is possible to use &something/arity not just because &something/arity looks cool but also because it’s faster and I don’t have to thing whether Elixir/Erlang will eventually translate something else to this faster form.
11
Post #5
NobbZ

NobbZ

&foo/1 is slightly more efficient at the VM level than &foo(&1), as the latter has an additional function call indirection.

The compiler is free to translate one to the other depending on local vs. remote calls, to make it in average more efficient.

jawakarD

jawakarD

As far as I know, elixir will transform &something(&1) to fn x -> something(x) and then to &something/1, because, the body is just another call to a named function…

If any other things are happening in the function like: &(something(&1) + &2) It’ll be transformed to fn x,y -> something(x) + y end

So to answer your questions:

it’s nice to mentally translate & to fn x -> . BUT, can I always do that?

Here you can’t map & to fn x -> mostly because, it depends on arity of the function. If you’re writing a fn like &(&1 + &2 + &3) you can make a mind map of fn x, y, z -> .. end. If you already aware of that then it’s fine.

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?

Yes, same because all of them can be used interchangebly,

But to be clear:
If the fn expects more arguments like &(something(&1, &2), it is same as &something/2. Notice that the parameters has to be in order, if not, &(something(&2, &1) is not same as &something/2 but transformed into fn x,y -> something(y,x) end

May I always look at cryptic &something/1 and say that this is just abbreviation of fn x -> something(x) end ?

You can say that.

Let’s say we are passing an anonymous function as a perameter Enum.reduce([1,2,3,4,5], &(&1 + &2)), reduce will likely to call fn.(x,y) which is mapped to &:erlang.+/2 which happened after an attempt to tranform into fn x, y -> x + y end and elixir saw an oppertunity for optimization.

Where Next?

Popular in Questions Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New
Mooodi
Given a string, how can I get access to its character by index? Enum.at("my_string", 2) doesn't work. Or rather, not char, but a substr...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
AstonJ
You’re a programmer, so you don’t need spoon feeding with the conventional drivel about “this is an integer.” No. You need to know what’s...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New

We're in Beta

About us Mission Statement