Saturday, April 20, 2024
HomeProgrammingHow To Use Modules and Features in Elixir | by Eduardo Rico...

How To Use Modules and Features in Elixir | by Eduardo Rico Sotomayor | Sep, 2022


A short information to exploring these ideas

Taken from https://elixir-lang.org/

On this sequence, we have now used a number of modules corresponding to String and Map, this time we are going to see create our personal modules.

In precept, they’re similar to lessons; nonetheless, they don’t have any state.

The essential syntax of the modules is as follows:

Module primary syntax

Throughout the modules we will discover, amongst different issues, two sorts of capabilities: the general public capabilities that may be accessed in different modules (and inside iex), and the personal capabilities that may solely be executed in the identical module. It is very important keep in mind that capabilities return the final line of code.

Operate inside a module

To run this module, we have now to compile it. So, in our terminal, on the degree the place the module is positioned (I known as it math.ex), we execute the next:

This returns us the bytecode of our module, and that’s mechanically obtainable in our Elixir interactive shell. This occurs once we are in the identical listing because the module, so if we put

after which

it returns 3.

One other method to execute it’s to position the module in an exs file, the place the bytecode is saved in reminiscence and there’s no have to compile it. You solely must print on the display the results of the execution of the module operate.

And run it with the command elixir

We will compile and import Elixir information contained in the interactive shell. We place the next within the iex:

On this manner, we will additionally name capabilities of our module

Features can have wards and clauses. Let’s see a operate that checks if a quantity is zero when it’s int. Right here’s the code:

We will even have default values. Let’s see an instance with strings:

Then run the file after compiling it in iex

When we have now a number of clauses within the operate, it’s helpful to make use of a header operate that defines the default values after which wards to enter one or one other operate.

On this manner, if we ship just one argument, a, the argument, b, takes the worth of nil, and subsequently, the be a part of operate is executed — which solely returns a.

Thanks for studying! Keep tuned for extra.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments