Using Erlang in Elixir

elixir, erlang

A quick demonstration of using a native Erlang library in Elixir.

July 29, 2017

Erlang is a first-class citizen of Elixir. This isn’t a surprise; Elixir compiles down to BEAM, Erlang’s VM, which means we get to leverage the power of Erlang for free.

We can see this functionality demonstrated in translating an Erlang library function into Elixir code. First, a look at the Erlang version:

client() ->
    SomeHostInNet = "localhost", % to make it runnable on one machine
    {ok, Sock} = gen_tcp:connect(SomeHostInNet, 5678, 
                                 [binary, {packet, 0}]),
    ok = gen_tcp:send(Sock, "Some Data"),
    ok = gen_tcp:close(Sock).

Probably most important to note is the syntax for calling an Erlang library in Elixir: :gen_tcp (note the colon). This lets Elixir’s compiler know that a call to a native Erlang libary will be performed. Now, in Erlang:

After converting the above, here is the Elixir implementation:

def client do
  some_host_in_net = "localhost" # to make it runnable on one machine
  {:ok, sock} = :gen_tcp.connect(some_host_in_net, 5678, [binary, {packet, 0}])
  :ok = :gen_tcp.send(sock, "Hello, World!")
  :ok = :gen_tcp.close(sock)

Once you understand some of the nuances of Erlang’s syntax, you can see that it’s a relatively straightforward exercise to convert methods between the two.