How To Define A Function In Elixir

Image for post
Image for post

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.

Image for post
Image for post

Let’s run our Vat.cro method in Elixir:

Image for post
Image for post

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

Our last statement was float value 0.25.

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

Image for post
Image for post

And run it in Iex:

Image for post
Image for post

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:

mix format various_modules.ex

Here is formater output:

Image for post
Image for post

Notice the new line between cro and hun functions.

Remember What You Learned

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

Written by

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