In part 6 of my Elixir journey I wanted to talk about organizing functions with modules.
Modules
So far my blog series about Elixir has almost exclusively made use of the anonymous function. They offer a beginner friendly on-ramp for anyone just starting with the language but most real software eventually requires additional organization. To accomplish this in Elixir we use modules and within those modules we use named functions.
defmodule Math do
def triple(n) do
n * 3
end
end
In this example we create a module definition using the `defmodule` keyword followed by the module name. Now that we have a module we can define what is known as a named function. This named function is defined using the `def` keyword followed by the function name.
There are a few ways we can interact with this module but today we'll be using IEx at the command line.
iex -S mix run foo.exs
IEx provides an interactive session that allows us to use the module and named functions directly from the terminal.
nine = Math.triple(3)
Traditionally we use the `do` and `end` syntax to group functions or modules but you may also write them using `do:` as shown below.
defmodule Math do
def triple(n), do: n * 3
end
It turns out the `do` and `end` syntax is syntactic sugar that makes organizing the block easier to read. The most extreme example without `do` and `end` looks something like this.
defmodule Math, do: (def triple(n), do: n * 3)
Using parentheses can unlock a single line module like you see above but I don't believe it's optimal for the reader. Any time you see the `do:` shorthand used with functions it's likely the body is trivial. For everything else I recommend the more explicit `do` and `end` syntax.