Erlang is a powerful, concurrent programming language designed for building scalable and fault-tolerant systems. Originally developed by Ericsson for telecommunications applications, Erlang has found applications in various domains due to its robust concurrency model and fault-tolerant features. Whether you are a beginner or an experienced developer, having a cheatsheet handy can be immensely helpful for quick reference. In this blog, we’ll provide a comprehensive Erlang cheatsheet to assist you in your coding endeavors.
1. Variables and Atoms
% Variables start with an uppercase letter or underscore
Variable = 42.
% Atoms are constants with a name
Atom = atom.
2. Data Types
% Integers
Number = 42.
% Floating-point
Float = 3.14.
% Atoms
Atom = atom.
% Strings (lists of integers)
String = "Hello, Erlang!".
% Lists
List = [1, 2, 3].
% Tuples
Tuple = {atom, 42}.
Functions
3. Function Definition
% Function to calculate the square of a number
square(X) ->
X * X.
4. Anonymous Functions (Fun)
% Anonymous function to double a number
Double = fun(X) -> X * 2 end.
Result = Double(5). % Result will be 10
5. Pattern Matching
% Function with pattern matching
is_zero(0) -> true;
is_zero(_) -> false.
Control Flow
6. Conditionals
% If statement
check_value(X) ->
if
X > 0 -> "Positive";
X < 0 -> "Negative";
true -> "Zero"
end.
7. Case Statement
% Case statement
classify_number(X) ->
case X of
0 -> "Zero";
N when N > 0 -> "Positive";
N when N < 0 -> "Negative"
end.
Concurrency
8. Processes
% Spawn a new process
spawn(fun() -> io:format("Hello, World!~n") end).
% Sending and receiving messages
Pid = spawn(fun() -> receive Msg -> io:format("Received: ~p~n", [Msg]) end end),
Pid ! "Hello, Process!".
9. OTP (Open Telecom Platform)
% GenServer Example
-module(my_server).
-behaviour(gen_server).
-export([start_link/0, init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
init([]) ->
{ok, []}.
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Error Handling
10. Try…Catch
% Try...Catch block
divide(X, Y) ->
try
Result = X / Y,
{ok, Result}
catch
error:badarith -> {error, "Bad arithmetic operation"};
_:_ -> {error, "An unexpected error occurred"}
end.
Modules and Libraries
11. Importing Modules
% Importing the lists module
-module(my_module).
-import(lists, [reverse/1, member/2]).
12. Common Libraries
% Working with lists
List1 = [1, 2, 3],
List2 = lists:reverse(List1).
% String manipulation
String = "Hello, Erlang!",
Length = string:len(String).
% File I/O
{ok, File} = file:open("example.txt", [read]),
Contents = file:read_line(File),
file:close(File).
This cheatsheet provides a quick reference for essential Erlang concepts. Keep in mind that Erlang has a rich set of libraries and tools, so exploring the official documentation is highly recommended for a deeper understanding of the language.
1. What is Erlang primarily used for?
Erlang was originally developed by Ericsson for telecommunication systems, but its strengths in concurrency, fault tolerance, and scalability have led to its adoption in various domains. Common applications include distributed and concurrent systems, real-time communication platforms, and large-scale network infrastructure.
2. How does Erlang handle concurrency?
Erlang follows a lightweight concurrency model using processes. Each process runs independently and communicates through message passing. This approach enables scalable and fault-tolerant systems. Processes are lightweight, allowing thousands to run concurrently without consuming excessive resources, making Erlang well-suited for building highly concurrent applications.
3. What is OTP in Erlang?
OTP (Open Telecom Platform) is a set of libraries, behaviors, and design principles built on top of Erlang. It provides a framework for building robust, fault-tolerant, and scalable applications. Key components include gen_server for generic server behavior, gen_fsm for finite state machines, and gen_event for event handling. OTP helps developers adhere to best practices and design patterns when building Erlang applications.
4. How does pattern matching work in Erlang?
Pattern matching is a fundamental concept in Erlang. It allows developers to destructure and match data against specific patterns. It is widely used in function heads, case statements, and receive blocks for message handling in processes. Patterns can include variables, literals, and complex data structures. Pattern matching simplifies code and enhances readability, making it easier to express complex logic concisely.
5. Can Erlang be used for web development?
Yes, Erlang can be used for web development. The most notable framework for web development in Erlang is Phoenix, built on the Elixir programming language. Phoenix provides a highly productive and scalable environment for building web applications, utilizing Erlang’s concurrency features and OTP for robustness. Erlang’s ability to handle concurrent connections and its fault-tolerant nature make it suitable for building reliable and high-performance web systems.