The def macro defines a named function inside a module from its name, argument list, and body. Functions return the value of their last expression, without an explicit return. section 2.3.2
Use def with these practical conventions:
- Name functions with lowercase letters or underscores; use ? for boolean-oriented names and ! for functions that may raise errors. section 2.3.2
- Omit parentheses for zero-argument functions, and use the condensed one-line form when the body has one expression. section 2.3.2
- Define public functions with def; use defp when a helper must remain private to its module. section 2.3.4
Public and private functions
A module can export double while hiding its sum helper: def double(a) do sum(a, a) end; defp sum(a, b) do a + b end. TestPrivate.double(3) returns 6, while calling TestPrivate.sum(3, 4) fails. section 2.3.4
defmodule Geometry do
def rectangle_area(a, b) do #1
... #2
end
end
A minimal module shows the required relationship between def, a function name, arguments, and a do...end body. section 2.3.2
