Variables and Atoms

% Variables start with an uppercase letter or underscore

Variable = 42.

% Atoms are constants with a name

Atom = atom.

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

Function Definition

% Function to calculate the square of a number
square(X) ->
    X * X.

Anonymous Functions (Fun)

% Anonymous function to double a number
Double = fun(X) -> X * 2 end.
Result = Double(5). % Result will be 10

Pattern Matching

% Function with pattern matching
is_zero(0) -> true;
is_zero(_) -> false.

Control Flow

Conditionals

% If statement
check_value(X) ->
    if
        X > 0 -> "Positive";
        X < 0 -> "Negative";
        true  -> "Zero"
    end.

Case Statement

% Case statement
classify_number(X) ->
    case X of
        0 -> "Zero";
        N when N > 0 -> "Positive";
        N when N < 0 -> "Negative"
    end.

Concurrency

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!".

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

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

Importing Modules

% Importing the lists module
-module(my_module).
-import(lists, [reverse/1, member/2]).

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.