concept function in category elixir

appears as: functions, function, A function, function, functions, The functions, The function
Phoenix in Action

This is an excerpt from Manning's book Phoenix in Action.

Functional programming is all about data transformation. Mutable (changeable) data and changing state are avoided (and in some cases are impossible). A function that’s called with the same parameters any number of times will return the same answer every time. In purely functional code, no data outside of that function will be considered when the return value is computed. One of the results of this is that the return values of functions need to be captured in order to be used again—there’s no object involved that encapsulates its own state.

Before we begin writing Elixir, I’ll show you a quick example of what a module might look like (a module can be thought of as a collection of functions). Have you heard of the “fizz buzz” programming exercise? This is the basic idea:

That documentation is written just above the function declaration in the Elixir source code. Figure 2.2 is a screenshot of the source code for clear/0. You can see that the number of lines dedicated to documentation closely matches the number of lines of code for the function.

Figure 2.2. The source code and in-line documentation for clear/0

This is an example of a function with light documentation. The documentation can be extensive, sometimes running to dozens of lines with multiple examples. This makes reading Elixir source code files easy. It also makes discovering how to use new modules and functions easy!

2.1.5. Back to modules and named functions

Most of your code won’t be simple anonymous functions. You’ll be organizing and reusing large portions of your codebase. To keep things organized, you can group functions that have things in common into modules. For example, if you had a group of functions that did mathematical calculations, you might group them together in a Math module. Let’s look at a few interesting aspects of modules.

In the following listing, you have one even_numbers function that expects two arguments and another that accepts zero or one arguments—functions can have default argument values, specified by the \\ characters. You can call even_numbers with a single number and have it find even numbers from 0 to the provided number, or you can call it with no arguments and have it default to returning even numbers from 0 to 10. Stylistically, functions with the same name are grouped together.

Listing 2.12. Demonstrating function overloading
defmodule Math do
  def even_numbers(min, max) do
    Enum.filter(min..max, fn(x) -> rem(x, 2) == 0 end)    #1
  end
  def even_numbers(max \\ 10) do
    even_numbers(0, max)                                  #2
  end
end

Functions inside a module can call other functions inside the same module without using the module prefix. If there’s ever a cause for confusion over function names, you can use the full name of the function (Math.even_numbers) instead.

Functions that you need to call internally but that you don’t want exposed to the outside world, can be defined as private. You do this by using defp instead of def when defining the function.

defp internal_calculation(x), do: 42 + x

The following listing shows what our group of functions that deal with simple calculations might look like now.

Elixir in Action

This is an excerpt from Manning's book Elixir in Action.

Both Erlang and Elixir are functional languages. They rely on immutable data and functions that transform data. One of the supposed benefits of this approach is that code is divided into many small, reusable, composable functions.

A function must always be a part of a module. Function names follow the same conventions as variables: they start with a lowercase letter or underscore character, followed by a combination of alphanumerics and underscores.

As with variables, function names can end with the ? and ! characters. The ? character is often used to indicate a function that returns either true or false. Placing the character ! at the end of the name indicates a function that may raise a runtime error. Both of these are conventions, rather than rules, but it’s best to follow them and respect the community style.

If a function has no arguments, you can omit the parentheses:

defmodule Program do
  def run do
    ...
  end
end

What about the return value? Recall that in Elixir, everything that has a return value is an expression. The return value of a function is the return value of its last expression. There’s no explicit return in Elixir.

The Little Elixir & OTP Guidebook

This is an excerpt from Manning's book The Little Elixir & OTP Guidebook.

Although Elixir may not be the best language in which to write scripts, it includes familiar-sounding libraries such as Path and File. The documentation is also a joy to use. Explanations are clear and concise, with examples of how to use the various libraries and functions.

Want to know the functions available in Dict? Type Dict. (the dot is important!), and then press the Tab key. You’ll see a list of functions available in the Dict module, as shown in figure 2.2.

Figure 2.2. A list of functions available in the Dict module

2.3.1. Modules, functions, and function clauses

Modules are Elixir’s way of grouping functions together. Examples of modules are List, String, and, of course, MeterToFootConverter. You create a module using defmodule. Similarly, you create functions using def.

Just for kicks, let’s write a function to convert meters into inches. You need to make a few changes in the current implementation. First, the module name is too specific. Let’s change that to something more general:

defmodule MeterToLengthConverter do
  # ...
end

More interestingly, how do you add a function that converts from meters to inches? The next listing shows one possible approach.

Elixir in Action

This is an excerpt from Manning's book Elixir in Action.

1.2.2. Composing functions

Both Erlang and Elixir are functional languages. They rely on immutable data and functions that transform data. One of the supposed benefits of this approach is that code is divided into many small, reusable, composable functions.

A function must always be a part of a module. Function names follow the same conventions as variables: they start with a lowercase letter or underscore character, followed by a combination of alphanumerics and underscores.

As with variables, function names can end with the characters ? and !. The ? character is often used to indicate a function that returns either true or false. Placing the character ! at the end of the name indicates a function that may raise a runtime error. Both of these are conventions, rather than rules, but it’s best to follow them and respect the community style.

Personally, I find that omitting parentheses makes the code ambiguous, so my advice is to always include them when calling a function. The exception is a function that has no arguments. In this case, parentheses only increase the noise, so it’s better to omit them.

If a function resides in the same module, you can omit the module prefix:

Given that Elixir is a functional language, you often need to combine functions, passing the result of one function as the argument to the next one. Elixir comes with a built-in operator |>, called the pipeline operator, that does exactly this:

Once the system is started, you run some code, typically by calling functions from modules. How does the runtime access the code? The VM keeps track of all modules loaded in memory. When you call a function from a module, BEAM first checks whether the module is loaded. If it is, then the code of the corresponding function is executed. Otherwise, the VM tries to find the compiled module file—the bytecode—on the disk and then load it and execute the function.

Somewhat related to this discussion is the ability to dynamically call functions at runtime. This can be done with the help of the Kernel.apply/3 function:

iex(1)> apply(IO, :puts, ["Dynamic function call."])
Dynamic function call.

Kernel.apply/3 receives three arguments: the module atom, the function atom, and the list of arguments passed to the function. Together, these three arguments, often called MFA (for module, function, arguments), contain all the information needed to call an exported (public) function. Kernel.apply/3 can be useful when you need to make a runtime decision about which function to call.