Functions in Elixir

Functions are central in Elixir. We’ll learn about functions with a few different examples.

defmodule Example do
  # Here's a function that takes two integers and returns
  # their sum as an integer.
  def plus(a, b) do
    a + b
  end

  # In Elixir, functions automatically return the value of their last expression,
  # so we don't need an explicit return statement.

  # When you have multiple parameters, you can simply list them.
  # Elixir will infer their types.
  def plus_plus(a, b, c) do
    a + b + c
  end
end

# Call a function using the module name followed by a dot and the function name.
res = Example.plus(1, 2)
IO.puts("1+2 = #{res}")

res = Example.plus_plus(1, 2, 3)
IO.puts("1+2+3 = #{res}")

To run this Elixir code, you would typically save it in a file (e.g., functions.exs) and then use the elixir command:

$ elixir functions.exs
1+2 = 3
1+2+3 = 6

In Elixir, functions are defined within modules. The defmodule keyword is used to define a module, and def is used to define a function within that module.

Elixir is a functional programming language, so functions are first-class citizens. It has some key differences from imperative languages:

  1. Functions automatically return the value of their last expression.
  2. There’s no need to specify parameter or return types - Elixir is dynamically typed.
  3. Function calls on modules use dot notation (e.g., Example.plus(1, 2)).

Elixir also supports many other powerful features related to functions, such as pattern matching, guards, and default arguments, which we’ll explore in later examples.