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

albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
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
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
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
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
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
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
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
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
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
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
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