Today I concluded the chapter on Anoymous Functions.

Creating an anonymous function

You create an anonymous function using the fn keyword. This is how your function block will look like:

var = fn
    parameter-list -> body
    parameter-list -> body

Here is an example of a function:

sum = fn
    a, b -> a + b

There are different ways of writing the above function, one of which is:

sum = fn (a, b) -> a + b end

Here is what we are doing above:

  • Define a function and tie it to the variable called sum
  • Pass in two parameter that get expressed by adding them together after ->
  • The function block gets terminated with the end keyword

Calling a function

Here is a sample of how you call a function in Elixir:


When calling a function, you must add the dot notation and parentheses, which is compulsory even if you are not passing in a value.

About the value, from the function call above it will look like we are assigning 4 and 5 as values of the variables a and b. That is not true, as there are no assignment in Elixir! Yea. Elixir uses what is called Pattern Matching. I’ll cover that in depth later.

There are other exciting things under anonymous function like; passing a function as a parameter into another function. Here is a quick example:

names = fn
  first_name -> fn
    last_name -> "#{first_name} #{last_name}" 

In the above a function tied to the variable names is defined. That function receives one parameter called first_name. In the body it executes another function which receives a parameter called last_name. The body of the inner function matches the both parameters into the evaluated expression. When we call names.("Kingsley") is returns the other function. When we run names.("Kingsley).("Silas") it returns the Kingsley Silas.

That will be all for now :)