Module
Elixir is a functional programming language. Module is used to group functions, like namespace in Clojure.
defmodule Calculator do
@moduledoc """
A simple module
"""
@doc """
Adds two numbers together.
## Examples
iex> Calculator.add(2, 3)
5
"""
def add(a, b) do
a + b
end
end
import
Modules can be used in other modules directly like Calculator.add.
With import, you can get rid of the prefix.
defmodule MyApp do
import Calculator
def sum(a, b, c) do
# Call add directly instead of Calculator.add
add(add(a, b), c)
end
end
Only import specific functions:
defmodule MyApp do
import Calculator, only: [add: 2]
end
use
use is more powerful.
When use SomeModule is encountered, the __using__/1 macro defined in that module will be called, which can then inject code into the current module.
defmodule Greeter do
defmacro __using__(opts) do
quote do
def hello(name) do
"Hello, #{name}!"
end
def greeting_type do
unquote(opts[:type] || "formal")
end
end
end
end
Use it in another module:
defmodule MyApp do
use Greeter, type: "casual"
def greet(name) do
hello(name) <> " Welcome to #{greeting_type()} chat."
end
end
Module Resolving
When you import or use a module, Elixir doesn't directly look for
files - it looks for compiled modules that are available in the
current compilation context. Loading paths can be inspected using :code.get_path.
iex -S mix
:code.get_path
Elixir follows a naming convention:
- Module names use
PascalCase - Filenames use
snake_case.ex - Nested modules (like
MyApp.User) map to directories (my_app/user.ex)