Named Functions and Modules

Learn about Elixir's named functions and how we can create our own.

We’ve covered how to create anonymous functions. We can bind them to variables, use them as arguments, and return them in functions. However, having only anonymous functions can be annoying. If the codebase of a large application used only anonymous functions, it would be very complex. Programming languages have many predefined words that we can use anywhere in the code to solve this issue. These predefined words in Elixir can be special forms, named functions, or macros. We can also create our own named functions.

Introduction to named functions

Named functions are defined inside of modules in Elixir. We can use an atom or aliases to name a module. An alias in Elixir is any word that starts with a capital letter, only ASCII characters are allowed—for example, String, Integer, Enum, or IO. All aliases will transform into atoms during compile time with an Elixir prefix. Try the following command in the IEx shell.

iex> String == :"Elixir.String" 
#Output -> true

Note that the atom :"Elixir.String" must have quotes because of the special character—in this example, we’re using a dot. We can invoke a function module by typing the name of the module and the function’s name using the dot operator between them. Try it in the IEx shell below:

iex> String.upcase("I'm using a module!") 
#Output -> "I'M USING A MODULE!"

We can omit the parentheses by calling named functions. It’s a matter of style over functionality. We should omit the parentheses when we want the code to be more readable, as in this example:

iex> IO.puts "Sometimes omitting the parentheses is better."

Calling named functions is similar to calling anonymous functions, and we’ll look at that next.

Get hands-on with 1200+ tech skills courses.