oliveiragahenrique

oliveiragahenrique

Anonymous function style

I’m current learning Elixir by the book Elixir in Action 2nd Edition. On chapter 3 at Stream functions exercises i’ve solved them a bit different from the original repository.

Problem: Get the longest line length of a file

Book resoluiton:

  def longest_line_length!(path) do
    path
    |> Stream.map(&String.replace(&1, "\n", ""))
    |> Stream.map(&String.length/1)
    |> Enum.max()
  end

My resolution:

  def longest_line_length!(path) do
    File.stream!(path)
    |> Stream.map(&String.replace(&1, "\n", ""))
    |> Stream.map(&String.length(&1))
    |> Enum.max()
  end

Is there some fundamental difference between Stream.map(&String.length/1) and Stream.map(&String.length(&1)) ?

Or it is just a style preference?

Personally I think it’s more clear to use &1 even if it’s not necessary. Maybe it is just because I’m still getting used with the language. Any thoughts?

Marked As Solved

NobbZ

NobbZ

It’s not that that function is called twice, but it causes two function calls.

Using &f(&1) needs to first call the anonymous function which calls then the inner function call. Using &f/1 creates a more direct “reference” to the target function and therefore removes one level of indirection.

Also Liked

Marcus

Marcus

But something like this will be optimised by the compiler.
For example:

  def foo(map) do
    map
    |> Enum.map(&String.upcase/1)
    |> Enum.map(&String.upcase(&1))
  end

becomes

foo(_map@1) ->
    'Elixir.Enum':map(
      'Elixir.Enum':map(_map@1, fun 'Elixir.String':upcase/1),
      fun 'Elixir.String':upcase/1).

But &String.upcase/1 should be the preferred form.

shanesveller

shanesveller

Besides the points above, if you’re not reordering or transforming arguments before calling the existing function, the Mod.fun/arity style is more succinct to read and write, especially for functions with arity > 1. fun(&1, &2, &3) is repetitive in a way that isn’t productive.

srowley

srowley

I had the same reaction and preference when I first started learning Elixir. There may be some real difference between them that I am not aware of; I just think of it as a style difference.

Over time as I got accustomed to referring to a function as Module.function/arity, the former syntax (i.e. &String.length/1) became more natural and the latter started to feel redundant/unnecessary.

Where Next?

Popular in Questions Top

Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
Phillipp
Hey, I have a NanoPi-M3 and try to install Elixir on their Ubuntu image. I followed the Raspberry Pi installation instructions from the ...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

Other popular topics Top

lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
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
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
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
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
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement