How to define functions and modules in Elixir

As Elixir is a functional language, functions play a significant role in developing Elixir applications. Typically, many little functions operate on data in functional language applications.

Let’s learn how to define functions and how we may organize them using modules.

For example, let’s suppose we have a valid? function, which tests if something is valid and returns a boolean response. Let’s also suppose we have a check! function, which does the checking and throws a runtime error if the check fails.

In Elixir, a function ending with ? does not require a return boolean value. Moreover, using ! indicates that an exception will be thrown if something goes wrong. These are commonly used norms among developers. Thus, following these is usually recommended because it makes understanding Elixir code much easier for other developers.

Here is what an essential function definition looks like:

def sum(a, b) do
  a + b
end

Modules in Elixir

Modules provide the namespace for functions and other items declared inside modules. These are usually grouped if they have the same meaning.

Elixir, for example, includes a set of functions for working with the Enum module’s enumerables. In addition, the IO module offers functions for dealing with input/output operations.

Modules in Elixir are defined using the defmodule keyword, followed by the module’s name and a bloc, which includes the module’s body.

defmodule educative do
  def print do
    IO.puts "i am learning"
  end
end

When calling a function inside the module, we can use the ModuleName.function_name format, as in line 11 below:

defmodule SampleModule do # Modules
def print do # function
IO.puts "Hello module"
end
end
SampleModule.print

A module can also be defined inside another module. Then, a function can be called inside the inner module using the dot separator between the module names, as in line 23 below:

defmodule SampleModuleOuter do # Module
defmodule SampleModuleInner do # Module
def print(content) do #function
IO.puts content
end
end
def print do
SampleModuleInner.print "Hello module"
end
end
# calling the nested module funtion
SampleModuleOuter.SampleModuleInner.print "Hello module"

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved