Elixir Named Functions
A named function is a reusable block of code with a name, stored inside a module. A module is a named container that groups related functions together.
A short form function greets a name
The short form fits one simple result on a single line. The value after do: is the result the function returns.
defmodule Greeter do
def hello(name), do: "Hello, #{name}"
end
IO.puts(Greeter.hello("Ana"))A long form function adds two numbers
The long form spreads the body over several lines between do and end. The last value in the body is the result.
defmodule Calculator do
def add(a, b) do
a + b
end
end
IO.puts(Calculator.add(3, 4))A private helper works inside its own module
defp defines a private function, which means only code inside the same module can call it. The public function below uses the private helper to do part of its work.
defmodule Greeter do
def hello(name), do: shout(name)
defp shout(name), do: String.upcase(name)
end
IO.puts(Greeter.hello("Ana"))Example
defmodule Report do
def title(name), do: "Report for #{name}"
def score(points) do
points + bonus(points)
end
defp bonus(points), do: div(points, 10)
end
IO.puts(Report.title("Ana"))
IO.puts(Report.score(50))Key points
- Module: a named container that groups related functions together.
- defmodule: starts a module definition and gives the module its name.
- def: defines a public named function that code outside the module can call.
- Calling: write the module name, a dot, and the function name, as in Greeter.hello("Ana").
- Short form: a one-line function uses def, the name, and do: followed by the result.
- Long form: a function that needs more room uses do, the body lines, and end.
In this example, Report.title uses the short form and Report.score uses the long form. The score function calls the private bonus helper, which adds one tenth of 50, so the total is 55.
Note
in Elixir, a named function always belongs to a module.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does Greeter.hello("Bo") print when hello is defined as def hello(name), do: "Hello, #{name}"?