links: Elixir MOC


Functions that return a boolean value

In Elixir, any functions that return a boolean value will follow a trailing question mark naming convention (?)

Examples: PacMan.win?/3, Mix.debug?/0, String.contains?/2

Anonymous functions

Anonymous functions are commonly used throughout elixir on their own

  • as return values
  • as arguments in higher order functions such as Enum.map/2
Enum.map([1, 2, 3], fn n -> n + 1 end)
# => [2, 3, 4]

Functions in Elixir are treated as first-class citizens

  • Names and anonymous functions can be assigned to variables
  • Names and anonymous can be passed around like data as arguments and return values
  • Anonymous functions can be created dynamically

Anonymous functions are created with fn keyword and invoked with a dot (.)

func_var = fn n -> n + 1 end
func_var.(1)
# => 2

Anonymous functions may be created with & capture shorthand

  • The initial & declares the state of the capture expression
  • &1 , &2 and so on refers to the positional arguments of the anonymous function
# Instead of
fn x, y -> abs(x) + abs(y) end
 
# we can write
& abs(&1) + abs(&2)
  • The & capture operator can also be used to capture existing named functions
# Instead of
less_than = fn a, b -> a <= b end
 
# we can write
less_than = &<=/2

Anonymous functions in Elixir are Closures. They can access variables that are in the scope when the function is defined. Variables assigned inside of an anonymous function are not accessible outside of it

y = 2
 
square = fn ->
  x = 3
  x * y
end
 
square.()
# => 6
 
x
# => ** (CompileError): undefined function x/0

Named Functions

  • All named functions must be defined in a module
    • Named functions are defined with def
    • A named function may be made private by using defp instead
    • The value of the last expression in a function is implicitly returned
    • Shorthand functions may also be written using a one-line syntax
def add(a, b) do
  a + b
end
 
defp private_add(a, b) do
  a + b
end
 
def short_add(a, b), do: a + b
  • Functions are invoked with the full name of the function with the module name
    • if it’s invoked from within it’s own module, the module name may be omitted
  • The arity of a function is often used when referring to named function
    • The arity refers to the number of arguments it accepts
def add(x, y, z) do
  x + y + z
end

Concepts around functions


tags: elixir function

sources: