In Elixir, functions are first class types. This shouldn't be terribly surprising; it is a functional programming language, after all. Today, we'll have a look at:

  • Defining Anonymous Functions
  • Calling Anonymous Functions
  • Using Functions as first class types

Let's get started.

Anonymous functions are defined with the fn keyword. Let's see what that looks like:

print_name = fn {:person, first_name, last_name} -> first_name <> " " <> last_name end

Functions take parameter lists and bodies, separated by arrows (->). The parameter lists are used for Pattern Matching (we actually saw function declaration in the last episode on Pattern Matching).

The print_name function above will match a tuple containing three elements, when the first element is the atom :person. It then matches to a body that will concatenate the first and last names together (where by convention, we assume they will be in the second and third positions in the tuple).

The syntax...