Now that you’ve run your first Erlang program, it’s time to dive deeper into its core components: Erlang functions and its unique data types. As a functional language, everything in Erlang revolves around functions. Understanding how they work, along with the immutable data structures they operate on, is key to mastering the language and its concurrent capabilities.
💻 Core Erlang Data Types
Erlang has several fundamental data types. A key concept is immutability, meaning once a variable is assigned, its value cannot be changed.
- Numbers: Erlang supports integers (e.g.,
123
) and floats (e.g.,0.987
). - Atoms: These are constants where the value is the name itself, like
linux
orok
. They are used to represent distinct, non-numeric values. - Tuples: A fixed-size, compound data type for grouping a number of items, enclosed in curly braces: {linux, 1}.
- Lists: A variable-size, compound data type, enclosed in square brackets:
[a, b, 3, {a, b}]
. Strings in Erlang are simply lists of characters. - Maps: A key-value data structure, perfect for storing associative data:
#{country => greece, city => athens}
.
💻 Working with Functions
Functions in Erlang are sequences of clauses separated by semicolons and ending with a period. A function’s identity is defined by its name and its arity (number of arguments), written as functionName/arity
. Erlang also supports anonymous functions, also known as ‘funs’, which can be assigned to variables and passed as arguments to other functions.
F = fun(X) -> 2 * X end.
Five = fun(N, Function) -> 5 * Function(N) end.
Five(10, F).
In this example:
F
is an anonymous function that doubles its input.Five
is an anonymous function that takes a numberN
and another functionFunction
as arguments.Five(10, F)
callsFive
, which in turn callsF(10)
and multiplies the result by 5, yielding100
.
Erlang also relies heavily on pattern matching and guards within function clauses to control program flow, which is often used in place of traditional if/else statements.
More Topics
- Redis Guide: The High-Speed In-Memory Data Store
- Riak NoSQL Guide: What’s the Big Deal?
- MongoDB Guide: Build a Blog with Python and Bottle
- MongoDB Guide: An Admin’s Guide to Maximum Power
- MongoDB Guide: Using Native Drivers with Python and Ruby
- MariaDB Guide: The Open Source MySQL Alternative
- SQLite3 Guide: Getting Started with Python