Erlang Cheat Sheet
(this is a work in progress)
Getting the interpreter in ubuntu: sudo apt-get install erlang. To
get native compliation capability, also install erlang-base-hipe.
Starting the interpreter: erl. To exit: Ctrl-g then q enter.
File extension: .erl.
Compiling a module from the shell (assuming the module is in the
current directory): c(module_name). If hipe is installed, native
compliation can be done with c(module_name, [native]).
Add .beam to the project's .gitignore.
- Start a shell:
C-c C-z - Compile file:
C-c C-k
Statements end in ..
Variables start with an upper case letter, atoms start with a lowercase one.
- Mod operator:
5 rem 2 - Integer division:
5 div 2 - Equality testing:
x =:= 2 - Pattern patching:
{foo, X} = {foo, 123}.(X becomes123)
- Functions with the same name but a different number of arguments are
considered different functions.
- e.g.
add/2vsadd/3for referring to the 2- and 3-argument variants
- e.g.
Example:
add(A,B) ->
A + B.Point = {123,456}.
{X,Y} = Point.
{X,_} = Point.
Lists can be mixed-type.
- List of numbers:
[1, 2, 3] - Prepend to a list
[0 | numbers] - Get head and tail:
[H, T] = Numbers. - Comprehensions:
[2*N || N <- [1,2,3,4]]. - Range:
lists:seq(1, 4).
- Declare a module called foo:
-module(foo). - Export a function:
-export([add/2]). - Import a module and some functions:
-import(foo, [add/2]). - Calling a function from a module:
foo:add(1,2).
- Strongly typed (no implicit type conversions)
- Dynamically typed
erlang:list_to_integer("54")(strings are basically lists of numbers in erlang)erlang:integer_to_list(54)erlang:atom_to_list(true)
- Atoms (e.g.
foo,true) - Bit strings