How To Define A Module In Elixir

How To Define A Module In Elixir

FacebookTwitterRedditHacker NewsLinkedInEmailShare

Reading Time: 3 minutes

Image for post
Image for post

TL;DR

Modules are way how to group Elixir functions in meaningful groups. This post is part of the functional language series.

In Elixir, the module is starting block. Elixir is a functional programming language, which means that everything happens in functions. Elixir creators decided that Elixir’s function must have a module.

Let's create a string from number 46 using the Integer module that comes with Elixir.
Image for post
Image for post

Have you helped yourself with a magnificent TAB feature in Iex? Time to use your favorite editor and create an Elixir module. My favorite is vi editor, but in daily work, I use Visual Studio Code. Type and save text from the screenshot below.

Image for post
Image for post

Congratulations, you created your first Elixir module that does nothing for now. But you learned keywords:

defmodule – you announce to Elixir that you are creating a module. The module name goes next.
do – start of module
end – module definition ends here.

You will use do and end a lot. Module name has rules:

The file name is various_modules.ex where ex is Elixir’s file extension.

Lets’s use our module:

Image for post
Image for post

iex various_modules.ex makes our Vat module available in iex. Type Va and press tab. Voila, iex recognized Vat module by autocompleting its name. Although, we can do nothing with the module because there are no functions in it.

Let’s create several modules in the same file. A module could have submodules. We also could use dot notation.

Image for post
Image for post

Save it and run the file with iex. Type Salary and press Tab, you have two submodules. One due to having name with a dot, other due to being submodule.

Image for post
Image for post

Remember

  • In the module, we put functions.
  • How to load Elixir file in Iex
  • Module naming rule
  • Submodules and dot notation could help you in code organization.

Originally published at https://blog.tentamen.eu on April 29, 2020.

Written by

Founder of Tentamen, software testing agency.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store