Notes on Erlang
I’ve decided to start keeping my notes online so that I don’t have to flip through notebooks to find what I need. Some of this stuff is probably common sense and easily found in books or with online documentation, but I wanted to create a space to put my notes about the language. The notes will focus on Erlang langauge syntax, irregularities seen from the eyes of a C/C++ programmer, and libraries that are helpful.
A common beginner mistake
Variables must start with an uppercase letter. Atoms must start with a lowercase letter. The Eclipse plug-in for Erlang development highlights the variables in orange and does not highlight the atoms. This can be helpful when you’re just starting out with Erlang, especially if you’re coming from a language like C++/C#/Java where camel case is common for naming variables–its a tough habit to break!
Defining a constant
To define some constants in your program, in C/C++ one expects:
const double MAX_RATE = 9.78;
…
#define MAX_RETRIES 5
in Erlang, it should do the following:
-define(MAX_RATE, 9.78).
…
-define(MAX_RETRIES, 5).
On == versus =:=
A good discussion on this is available at the Trap Exit Erlang Forums. Basically though, when comparing a floating point number and an integer == will convert the integer for to a floating point and then do the comparison. However, =:= looks at the type, so comparing an integer and a floating point would fail since the types are not the same. It should also be noted that =:= provides more information to the Erlang compiler and some tools like Dialyzer.
“Hot plug” functionality
One should use spawn(Module, Function, Args) to spawn a new process if upgrading the function on a production system is required. One must *also* export the function in the module.
Useful libraries and functions
| io_lib:format | this function does C language sprintf() style formatting for strings |
| gen_tcp | BSD-socket style control for TCP sockets |
| inet:peername | takes a socket as its argument and returns a tumple containing the IP address of the other end of the socket as well as the port number |
| inet_parse:ntoa | an undocumented function that takes an IP address tupple as its argument and converts it to a string in the format of a dotted IP address (“xxx.xxx.xxx.xxx”) |
| gen_tcp:controlling_process | changes the socket ownership of a socket so that when one process ends the socket is not automatically closed. |