published: 28th of January 2021
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.
Functions are defined in Elixir with the def keyword.
# 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 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.
# 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)
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.
# 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
https://elixir-lang.org/crash-course.html#function-syntax
https://learning.oreilly.com/library/view/elixir-in-action/9781617295027/c02.xhtml
https://learning.oreilly.com/library/view/elixir-in-action/9781617295027/c03.xhtml