Elixir module attributes could be used as constants, or they have a particular purpose and could be accessed during the runtime. This post is part of the functional language series, and it is based on the remarkable book Elixir In Action by Sasa Juric.
Attribute as constant
Let’s add our
You can see that number 180 is used on lines 6 and 12, and this is our first candidate for module attribute.
We can try it in
Elixir has predefined attributes that are registered in the Elixir binary (compiled)
beam file and could be used in
runtime. What differs a great programmer from a mediocre one is how they document their work. Elixir module attributes are here to help you with documentation. Let’s explore
@doc module attributes.
To use it in
runtime), we first need to compile it. Run
elixirc in the folder where is your source code:
iex h function, you get values for
@doc attributes in runtime.
ex_doc is an elixir tool that, based on those two attributes, generates your project documentation.
As Elixir is a dynamic language, type mismatch could not be detected in compile time. Elixir has
@spec a module attribute that we use to define a function input/output parameter types. Why? There is a tool
dialyzer that is a static analysis tool, and it could detect type usage errors using
Our position and trials function have the same
@spec because they both have for input
integer, and output is Elixir
String struct (this is why we do not write just
@is used for module attributes
- how to document a module
- how to document a function
ex_doctool generates HTML documentation
- how to specify function input/output types
- how to use module attribute as constant
dialyzeris a static analysis tool that uses
Originally published at https://blog.tentamen.eu on June 23, 2020.