Skip to content
Modules and Functions
step 1/5

Reading — step 1 of 5

Learn

~1 min readFunctions and Modules

All named functions in Elixir live inside modules. The module name and function arity together identify a function — String.length/1 is the length function in String taking 1 argument.

defmodule Math do
    def square(n) do
        n * n
    end

    def double(n), do: n * 2   # one-line form
end

IO.puts Math.square(5)   # 25

Functions can have multiple clauses, dispatched by pattern:

defmodule Math do
    def factorial(0), do: 1
    def factorial(n) when n > 0, do: n * factorial(n - 1)
end

Anonymous functions use fn ... end and are called with a dot:

add = fn a, b -> a + b end
IO.puts add.(3, 4)

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…