What is the Elixir module?
Overview
Modules are used to organize functions into a namespace, as well as define named and private functions.
Modules are not classes. In modules, we don’t have constructors and destructors.
Syntax
defmodule module_name do
functions and other logic
end
Example
#Moduledefmodule Example dodef greeting(name) doIO.puts "Hello #{name}."endendExample.greeting "Elijah"
Code explanation
In the code above, we see the following:
-
In line 2, we create a module
Example. -
In lines 3-5, we create a
greetingfunction. -
In line 4, we set the logic of the function to output the greeting.
-
In line 7, we call the
Example.greeting "Elijah"that gives the greeting output.
Layering modules in Elixir allows us to namespace our functionality even more.
#Moduledefmodule Example.Greetings dodef morning(name) doIO.puts"Good morning #{name}."end#function definitiondef evening(name) doIO.puts"Good night #{name}."endendExample.Greetings.evening"Elijah"
Code explanation
In the code above, we see the following:
-
In line 2, we layer two modules
Example.Greetings. -
In lines 3-5, we create a
morningfunction to print the message “Good Morning”. -
In lines 7-9, we create a
eveningfunction to print the message “Good Evening”. -
In line 11, we call the
Example.Greetings.evening "Elijah"that gives the greeting output.