How To Define A Function In Elixir

TL;DR

It is time to meet the first-class citizens of Elixir, a function. This post is part of the functional language series.

Function lives in a module. We have already defined an Elixir module. Let’s define our first Elixir function. We are going to use Elixir def macro.

Remember. Elixir has a minimal set of keywords. Everything else is build using macros. Elixir macros are powerful metaprogramming Elixir concept. But also, not so simple. For now, remember that def is a macro, not a keyword.

Remember. Function names follow the same rule as variables. Function name that ends with denotes that function raises an exception instead of returning error value.

Let add function to our Vat module that will return Croatian Vat as the float.

Remember. The function that does not take any input could be defined without parenthesis. Also, you can always use parentheses.

Let’s run our method in Elixir:

Remember. Elixir does not use the keyword. The function returns the value of the last statement.

Our last statement was float value .

A function could be defined in one line. Let’s define Hungarian vat:

And run it in Iex:

Remember. You call the function defined in the module by first stating the module name, the, then the function name.

You can store function results in a variable.

Elixir could help you with code style using a mix format task. When you are done with coding and testing, run mix format task against your file:

Here is formater output:

Notice the new line between and functions.

Remember What You Learned

  • Elixir macro vs. keyword
  • function naming convention
  • convention for function names that end with
  • function input/output values
  • one-liners
  • the
  • store function result value in a variable
  • mix format task

Originally published at https://blog.tentamen.eu on May 15, 2020.

Founder of Tentamen, software testing agency.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store