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

Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
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
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

Other popular topics Top

TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
New
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
William
I would like to know that is there any online source for learning Phoenix Framework for building E-Commerce Store? Any advantage on build...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New

We're in Beta

About us Mission Statement