How to Create And Use Modules In Erlang?

11 minutes read

In Erlang, modules are used to organize and encapsulate related functions, types, and other code entities. Here is some information on creating and using modules in Erlang:

  1. Creating a Module: A module is defined in a file with the same name as the module and the ".erl" file extension. For example, a module named "my_module" should be defined in a file named "my_module.erl". At the beginning of the module file, use the "-module(ModuleName)." directive to declare the module name. For example, "-module(my_module)." Optionally, you can use the "-export([Function1/Arity, Function2/Arity, ...])." directive to specify which functions should be visible outside the module. Arity refers to the number of arguments a function takes. After the module declaration, write the functions, types, and other code entities within the module.
  2. Compiling and Loading a Module: To compile a module, use the "c(ModuleName)." command in the Erlang shell or run erlc command-line utility on the module file. This generates a compiled beam file with the same name as the module and the ".beam" file extension. For example, compiling "my_module.erl" generates "my_module.beam". To load a compiled module into the Erlang shell or within another module, use the "Module = module_name." command. This makes the functions and code entities defined in the module accessible.
  3. Using Functions from a Module: After loading a module, you can call its functions by using the module name followed by a colon and the function name, like "Module:Function(Args)." If the function was exported using the "-export" directive, you can directly call it without using the module name. For example, "Function(Args)."
  4. Calling Functions in Other Modules: To call a function defined in another module, whether standard library modules or user-defined modules, you need to either load the module as explained before or prefix the function call with the module name. It is a good practice to use fully qualified function calls to avoid ambiguities when two modules have functions with the same name.


That's a brief overview of creating and using modules in Erlang. Modules are a powerful abstraction that promotes code organization, reusability, and maintainability in Erlang applications.

Best Erlang Books to Read in 2024

1
Handbook of Neuroevolution Through Erlang

Rating is 5 out of 5

Handbook of Neuroevolution Through Erlang

2
Designing for Scalability with Erlang/OTP: Implement Robust, Fault-Tolerant Systems

Rating is 4.9 out of 5

Designing for Scalability with Erlang/OTP: Implement Robust, Fault-Tolerant Systems

3
Learn You Some Erlang for Great Good!: A Beginner's Guide

Rating is 4.8 out of 5

Learn You Some Erlang for Great Good!: A Beginner's Guide

4
Erlang Programming: A Concurrent Approach to Software Development

Rating is 4.7 out of 5

Erlang Programming: A Concurrent Approach to Software Development

5
Programming Erlang: Software for a Concurrent World

Rating is 4.6 out of 5

Programming Erlang: Software for a Concurrent World

6
Erlang and OTP in Action

Rating is 4.5 out of 5

Erlang and OTP in Action

7
Erlang and Elixir for Imperative Programmers

Rating is 4.4 out of 5

Erlang and Elixir for Imperative Programmers

8
Property-Based Testing with PropEr, Erlang, and Elixir: Find Bugs Before Your Users Do

Rating is 4.3 out of 5

Property-Based Testing with PropEr, Erlang, and Elixir: Find Bugs Before Your Users Do


How to export functions from a module in Erlang?

In Erlang, functions can be exported from a module in order to make them accessible to other modules or applications. Here's how you can export functions in Erlang:

  1. Create a new Erlang module or open an existing one. -module(my_module).
  2. Define the functions you want to export. Prefix them with the -export attribute, followed by a list of function names you want to export. -export([hello/0, add/2]). hello() -> io:format("Hello, World!~n"). add(X, Y) -> X + Y.
  3. Save the module with a .erl file extension. For example, save the module as my_module.erl.
  4. Compile the module using the Erlang shell or the erlc command-line utility. Using the Erlang shell: > c(my_module). Using the erlc utility: $ erlc my_module.erl This will generate an Erlang bytecode file (my_module.beam) that can be executed by the Erlang virtual machine.
  5. Once the module is compiled, you can use the exported functions from other modules or the Erlang shell. > my_module:hello(). Hello, World! > my_module:add(2, 3). 5


By exporting functions from a module, you can make them available to other modules or applications, enabling code reusability and modular development in Erlang.


How to include type specifications in Erlang modules?

To include type specifications in Erlang modules, you can use the -type keyword in a module. Here's how you can include type specifications in an Erlang module:

  1. Define a module using the module attribute. For example, to define a module called "my_module", add the following line at the beginning of your module file: -module(my_module).
  2. Use the -export_type/1 attribute to export the types that you define. For example, if you want to export a type called "point", add the following line: -export_type([point/0]).
  3. Use the -type keyword to define your type specifications. For example, to define a type specification for the "point" type, add the following line: -type point() :: {number(), number()}. In this example, the "point" type is defined as a tuple of two numbers.
  4. Use the -spec keyword to specify the type signature for functions in your module. For example, to specify the type signature for a function called "add_points/2" that takes two points and returns a point, add the following line: -spec add_points(point(), point()) -> point(). This specifies that the "add_points" function takes two arguments of type "point" and returns a value of type "point".


By including type specifications in your Erlang modules, you can improve code readability, catch type-related errors early, and benefit from tools like Dialyzer for static type analysis.


What is the purpose of the "-behaviour" attribute in Erlang modules?

The "-behavior" attribute in Erlang modules is used to define and enforce behavior specifications. It provides a way to specify that a module should adhere to a specific behavior defined by a behavior module.


The purpose of the "-behavior" attribute is to help developers write correct and well-defined code by specifying and constraining the capabilities and expected behavior of a module. It allows developers and the Erlang compiler to detect and highlight deviations from the defined behavior.


The behavior itself is defined by a behavior module, which contains a set of callback functions that the implementing module must define. The "-behavior" attribute in the implementing module references the behavior module and indicates that the module adheres to the specified behavior. This enables static analysis, documentation generation, and other tools to validate and analyze the adherence to the behavior specification.


Using behavior specifications promotes code reuse and helps maintain consistency across different modules implementing the same behavior. It also aids in error detection, as any deviation from the defined behavior will be reported during compilation or analysis.


Overall, the purpose of the "-behavior" attribute in Erlang modules is to provide a mechanism for module authors to define a standard behavior and for developers to adhere to and benefit from that behavior in their own code.


How to use records within Erlang modules?

In Erlang, records are used to define a structured data type with named fields. They offer a convenient way to group related data together.


Here are the steps to use records within Erlang modules:

  1. Define a record: In your Erlang module, define a record using the -record directive. This defines the structure of the record and its fields. For example, let's say you want to define a record for a person with fields like name, age, and city. You can define it as follows:
1
-record(person, {name, age, city}).


  1. Create a record instance: To create an instance of the record, use the # prefix followed by the record name and initialize the fields accordingly. For example, to create a person record instance:
1
Person = #person{name = "John", age = 30, city = "New York"}.


  1. Access record fields: To access the fields of a record, use the # prefix followed by the record name and its field name. For example, to access the name field of the Person record:
1
Name = Person#person.name.


  1. Update record fields: Records are immutable in Erlang, so to update a specific field, create a new record with the required changes. For example, to update the name field of the Person record:
1
UpdatedPerson = Person#person{name = "Jack"}.


  1. Pattern matching with records: You can use pattern matching to extract fields from records. For example, to match against the Person record and extract the name field:
1
2
handle_person(#person{name = Name, age = Age, city = City}) ->
    io:format("Name: ~p, Age: ~p, City: ~p~n", [Name, Age, City]).


That's it! You have now learned how to use records within Erlang modules. Records provide a convenient way to work with structured data and improve code readability.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

Erlang is a programming language that has gained popularity for developing scalable and fault-tolerant systems, including web applications. When it comes to web development, Erlang offers several frameworks and libraries that facilitate the process. Here is an...
To send and receive messages between Erlang processes, you can use the message-passing mechanism provided by the Erlang programming language. Here are the key points to understand:Process Identification: In Erlang, processes are identified by a unique process ...
To install Erlang on Windows, follow these steps:Visit the official Erlang website at www.erlang.org.Go to the "Download" section of the website.Choose the Windows option under the "OTP" (Open Telecom Platform) category.Select the latest versio...
To configure Docker to expose an Erlang node, you need to follow these steps:Create a Dockerfile: First, create a Dockerfile in your project directory. This file will specify the base image, dependencies, and configurations for your Docker container. Choose an...
Working with binary data in Erlang allows for efficient manipulation and processing of binary data structures. Erlang provides a set of built-in functions and syntax for working with binary data. Here are some important aspects of working with binary data in E...
There are several code formatters available for Erlang that can help ensure consistent and readable code formatting. Some popular options include:erl_tidy: This code formatter is included with Erlang/OTP and is the official formatter provided by the Erlang/OTP...