kokolegorille

kokolegorille

Different closure between Erlang and Elixir

Hello everyone,

Here is some erlang code I wanted to translate to Elixir… here is a simple example in the console.

$ erl
Erlang/OTP 22 [erts-10.4.4] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [hipe]

Eshell V10.4.4  (abort with ^G)
1> Pid=self().                            
<0.82.0>
2> Ref = monitor(process, Pid).              
#Ref<0.2147538226.2721841158.105393>
3> receive                                
3> {'DOWN', Ref, process, Pid, Why} -> Why
3> end.

and here is the Elixir version I came up with…

$ iex
Erlang/OTP 22 [erts-10.4.4] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [hipe]

Interactive Elixir (1.9.1) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> pid = self()
#PID<0.108.0>
iex(2)> ref = Process.monitor(pid)
#Reference<0.417878796.1379926020.235519>
iex(3)> receive do
...(3)> {:DOWN, ref, :process, pid, why} -> why            
...(3)> end
warning: variable "pid" is unused (if the variable is not meant to be used, prefix it with an underscore)
  iex:4

warning: variable "ref" is unused (if the variable is not meant to be used, prefix it with an underscore)
  iex:4

Code is quite similar, but in the Elixir version, ref and pid are not seen by the receive block, while the Erlang version will match on a ‘DOWN’ message where Ref and Pid are set.

Why is that different?

Thanks for taking time

Marked As Solved

hauleth

hauleth

Elixir allows to rebind the variables, so this is perfectly possible to do:

a = 1
a = 2

Which will then be translated to Erlang as a something like:

A@1 = 1
A@2 = 2

To have the same behaviour as in Erlang, you need to use pin operator (^):

a = 1
^a = 2 # will fail with no match

So in your case you need to write it as:

receive do
  {:DOWN, ^ref, :process, ^pid, why} -> why
end

To “pin down” the variables to their current binding instead of creating new ones.

Also Liked

al2o3cr

al2o3cr

Erlang doesn’t distinguish between binding a value and pattern-matching on an already-bound value (part of its Prolog heritage IIRC). Elixir disambiguates between these two cases with the ^ operator, referred to as the “pin operator”:

So this (from your example) binds new values to ref and pid:

receive do
  {:DOWN, ref, :process, pid, why} -> why
end

while this pins them to their already-bound values:

receive do
  {:DOWN, ^ref, :process, ^pid, why} -> why
end
kokolegorille

kokolegorille

Thanks, I forgot the pin :slight_smile:

kokolegorille

kokolegorille

Thanks, I need a :coffee: :slight_smile:

This is the full function

  def on_exit(pid, fun) do
    spawn(fn ->
      ref = Process.monitor(pid)
      receive do
        {:DOWN, ^ref, :process, ^pid, reason} -> fun.(reason)
      end
    end)
  end

Where Next?

Popular in Questions Top

Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
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
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
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
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
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; somethi...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
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

Other popular topics Top

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
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
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
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39297 209
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New

We're in Beta

About us Mission Statement