馃惂
Practical Elixir
  • 馃惀Welcome!
  • 馃惙Prerequisites
  • 馃惛Why functional programming?
  • 馃History of Elixir
  • 馃悪Elixir fundamentals
    • 馃悵Types
      • 馃悞Basic types
      • 馃List and tuples
      • 馃Keyword lists and maps
    • 馃Pattern matching
    • 馃惍Modules
    • 馃Functions
    • 馃ΝConditionals
    • 馃惓Recursion
    • 馃悥Enumerables
    • 馃Mix
  • 馃Web development with Elixir
    • 馃惁Directory structure
    • 馃ΔFirst steps
    • 馃Phoenix basics
    • 馃悾Viewing to-do list
    • 馃悢Adding dynamic behavior
    • 馃Data persistence
  • 馃悕Resources
Powered by GitBook
On this page
  • What are modules?
  • Your first module
  • Compiling files with modules
Edit on GitHub
  1. Elixir fundamentals

Modules

PreviousPattern matchingNextFunctions

Last updated 1 year ago

What are modules?

Modules are a way for developers to "package" like functions. For simplicity sake, you can think of modules as static classes/singletons that are initialized once when your program starts. There are other nuances behind how modules really work in Elixir but that is the fundamental behavior that you should think about at this stage.

Your first module

To define a new module, you can use the defmodule . This guide will not cover what macros are, but you can think of them as defining keywords with some behavior. Then, within the body of the module, you can define functions using the def macro. For this demonstration, we will continue using .exs (or Elixir scripts):

defmodule Math do
    def add(a, b) do
        a + b
    end
    
    def subtract(a, b) do
        a - b
    end
end

IO.puts(Math.add(5, 3))

Then, when you run this script, you will see 8 printed.

位 ~/Projects/practical-elixir-demo/ main* elixir modules.exs 
8

Compiling files with modules

If you are dealing with .ex files (as you normally would in larger projects), you can expect to compile these modules via the elixirc command. Then, running the iex command again with the resulting bytecode in the same folder will cause the Math module to be loaded.

位 ~/Projects/practical-elixir-demo/ main* elixirc math.ex
位 ~/Projects/practical-elixir-demo/ main* iex
iex(1)> Math.subtract(5, 3)
2

Normally, you should not have to manually compile Elixir files (mainly because it becomes unwieldy). Elixir comes with a built-in build tool called Mix that we will discuss later on.

馃悪
馃惍
macro