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.
defmodule module_name do
functions and other logic
end
#Moduledefmodule Example dodef greeting(name) doIO.puts "Hello #{name}."endendExample.greeting "Elijah"
In the code above, we see the following:
In line 2, we create a module Example
.
In lines 3-5, we create a greeting
function.
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"
In the code above, we see the following:
In line 2, we layer two modules Example.Greetings
.
In lines 3-5, we create a morning
function to print the message “Good Morning”.
In lines 7-9, we create a evening
function to print the message “Good Evening”.
In line 11, we call the Example.Greetings.evening "Elijah"
that gives the greeting output.