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
Vat.cro method in Elixir:
Remember. Elixir does not use the
returnkeyword. 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 result 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:
Notice the new line between
Remember What You Learned
- Elixir macro vs. keyword
- function naming convention
- convention for function names that end with
- function input/output values
- store function result value in a variable
- mix format task