benhoven

benhoven

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]

Showing Posts 1 to 4

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.

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 #2
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.

benhoven

benhoven OP

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 #4
— All posts loaded —

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
rahultumpala
Hello, I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews