Intro

A function is a unit of code that does a thing. With Elixir being a functional language, functions are a core tenant of the language.

Elixir has both named functions and anonymous functions.

Named Functions

Functions are defined in Elixir with the def keyword.

elixir
# Define a named function

def my_function do
  # Contents
end

# Define a named function that accepts arguments

def another_function(a, b) do
  # Do someting with "a" and "b"
end

# Define a named function that has default arguments

# default arguments use the double backslash (\\\\\) to define their value
def another_function(a, b \\\\\ 1) do
  # Do someting with "a" and "b"
end

# Define a private named function

defp my_function do
  # Contents
end

# Call a named function within a module

another_function("stuff", "things")

# Call a named function from another module

IO.puts("Beam me up Scotty!")

Anonymous Functions

Anonymous functions are like named functions except they don't have a name. An anonymous function can be assigned to a variable and passed around like an integer or a string.

elixir
# Anonymous function syntax

fn parameter(s) -> body end
  
# Define an anonymous function

add = fn a, b -> a + b end

# Call an anonymous function

add.(1, 2)

Multi-Clause Functions

Functions can be overloaded by defining a function with the same name but different number of parameters (arity). This generates a function with a different signature because function signatures are defined by both their name and arity.

elixir
# Define multiple functions with the same name, but different parameters

defmodule SomeModule do
  # some_funciton/2
  def some_function(a, b) do
    # Do someting with "a" and "b"
  end

  # some_function/3
  def some_function(a, b, c) do
    # Do someting with "a" and "b" and "c"
  end

  # default clause that is always matched and 
  # returns and error rather than raise an exception.
  def some_function(unknown) do
    {:error, {:unknown_param, unknown}}
  end
end

Considerations

  • Functions must be defined inside of a module.
  • Functions can start with a lowercase [a-z] or an underscore _
  • Functions can contain upper/lower case [a-zA-Z] and the _ underscore characters.
  • snake_case is the formatting convention used for function naming.
  • Functions can end with a question mark ? or an exclaimation mark !
  • Functions that end with a question mark ? should return a boolean true or false
  • Functions that end with an exclaimation mark ! may raise a runtime error.
  • Functions are identified by its containing module and both their name and arity . Arity is a fancy word for the number of arguments.
  • Private functions are only accessible from the module they exist in.
# elixir