hariharasudhan94

hariharasudhan94

Difference between anonymous and named functions?

Can Someone please explain difference between anonymous and named functions ? where we need to use Anonynous and Named functions?

From the Agents tutorial they use

@doc “”"
Gets a value from the bucket by key.
“”"
def get(bucket, key) do
Agent.get(bucket, &Map.get(&1, key))
end

in the above example they have used named function Map.get/3 as Anonymous function by using Capture opertaor. Is there any particular reason to use ?

Most Liked

peerreynders

peerreynders

As a statement that is incorrect. An anonymous function is attached to the module that creates it [source].

Execution of the anonymous function will force the module that created it to load - and if that module cannot be loaded, execution of the anonymous function will fail - no matter how simple that anonymous function might be.

Example session:

# File: alpha.ex
defmodule Alpha do

  def make_fun,
    do: fn -> "Greetings from module #{__MODULE__}" end

end

# File: bravo.ex
defmodule Bravo do
  def dessicate(fun, path) do
    File.write path, (:erlang.term_to_binary fun), [:binary]
  end

  def hydrate(path) do
    {:ok, content} = File.read path
    :erlang.binary_to_term content
  end
end

iex(1)> ls()
     alpha.ex
     bravo.ex
iex(2)> c("alpha.ex")
[Alpha]
iex(3)> c("bravo.ex")
[Bravo]
iex(4)> :code.is_loaded Alpha
{:file, :in_memory}
iex(5)> :code.is_loaded Bravo
{:file, :in_memory}
iex(6)> fun = Alpha.make_fun
#Function<0.111841791/0 in Alpha.make_fun/0>
iex(7)> fun.()
"Greetings from module Elixir.Alpha"
iex(8)> Bravo.dessicate fun, "greetings"
:ok
iex(9)> 
BREAK: (a)bort (c)ontinue (p)roc info (i)nfo (l)oaded
       (v)ersion (k)ill (D)b-tables (d)istribution
a
$ iex
iex(1)> ls()
      alpha.ex
      bravo.ex
      greetings
iex(2)> c("bravo.ex")
[Bravo]
iex(3)> :code.is_loaded Alpha
false
iex(4)> :code.is_loaded Bravo
{:file, :in_memory}
iex(5)> fun = Bravo.hydrate "greetings"
#Function<0.111841791/0 in Alpha>
iex(6)> fun.()
** (UndefinedFunctionError) undefined function
    #Function<0.111841791/0 in Alpha>()
iex(6)> c("alpha.ex")              
[Alpha]
iex(7)> fun.()       
"Greetings from module Elixir.Alpha"
iex(8)> :code.is_loaded Alpha          
{:file, :in_memory}
iex(9)> c("alpha.ex",".")              
warning: redefining module Alpha (current version defined in memory)
  alpha.ex:2
[Alpha]
iex(10)> c("bravo.ex",".")
warning: redefining module Bravo (current version defined in memory)
  bravo.ex:2
[Bravo]
iex(11)> ls()
     Elixir.Alpha.beam
     Elixir.Bravo.beam
     alpha.ex
     bravo.ex
     greetings
iex(12)> 
BREAK: (a)bort (c)ontinue (p)roc info (i)nfo (l)oaded
       (v)ersion (k)ill (D)b-tables (d)istribution
a
$ iex
iex(1)> ls()
     Elixir.Alpha.beam
     Elixir.Bravo.beam
     alpha.ex
     bravo.ex
     greetings
iex(2)> r(Bravo)
warning: redefining module Bravo (current version loaded from Elixir.Bravo.beam)
  bravo.ex:2

{:reloaded, Bravo, [Bravo]}
iex(3)> :code.is_loaded Alpha
false
iex(4)> :code.is_loaded Bravo
{:file, :in_memory}
iex(5)> fun = Bravo.hydrate "greetings"
#Function<0.111841791/0 in Alpha>
iex(6)> :code.is_loaded Alpha          
false
iex(7)> fun.()
"Greetings from module Elixir.Alpha"
iex(8)> :code.is_loaded Alpha
{:file, '/Users/wheatley/sbox/elx/trial/anon/Elixir.Alpha.beam'}
iex(9)>
kokolegorille

kokolegorille

Passing a function is so usual, that there is this & &1 notation, but it does not mean that Map.get is anonymous.

You can do like something like this with a more complex function

do_what_you_want = fn x -> # do some stuff end
map |> Enum.map(&do_what_you_want.(&1))

Otherwise, You should have done

map |> Enum.map(fn x -> # do some stuff end)

And note that

&Map.get(&1, key)

is equivalent to

fn x → Map.get(x, key) end

It is not equivalent to Map.get(x, key)

NobbZ

NobbZ

iex(1)> a = 1
1
iex(2)> f = fn -> IO.puts a end
#Function<...>
iex(3)> f.()
1
:ok
iex(4)> defmodule F do
...(4)>   def g, do: IO.puts(a)
...(4)> end
** (CompileError) iex:5: function a/0 undefined
... stripped ...

As you can see here, the defed function has no access to the a that was bound outside, its scope is therefore “empty”

Where Next?

Popular in Questions Top

chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call t...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
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 records...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
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

Other popular topics Top

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
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
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
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
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
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 47930 226
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New

We're in Beta

About us Mission Statement