Compiling a Module

Let’s look at two ways to compile this file and load it into IEx. First, if you’re at the command line, you can do this:

 $ iex times.exs
 iex>​ Times.double(4)
 8

Give IEx a source file’s name, and it compiles and loads the file before it displays a prompt.

If you’re already in IEx, you can use the c helper to compile your file without returning to the command line.

 iex>​ c ​"​​times.exs"
 [Times]
 iex>​ Times.double(4)
 8
 iex>​ Times.double(123)
 246

The line c "times.exs" compiles your source file and loads it into IEx. We then call the double function in the Times module a couple of times using Times.double.

What happens if we make our function fail by passing it a string rather than a number?

 iex>​ Times.double(​"​​cat"​)
 **​ (ArithmeticError) bad argument in arithmetic expression
  times.exs:3: Times.double/1

An exception (ArithmeticError) gets raised, and we see a stack backtrace. The first line tells us what went wrong (we tried to perform arithmetic on a string), and the next line tells us where. But look at what it writes for the name of our function: Times.double/1.

In Elixir a named function is identified by both its name and its number of parameters (its arity). Our double function takes one parameter, so Elixir knows it as double/1. If we had another version of double that took three parameters, it would be known as double/3. These two functions are totally separate as far as Elixir is concerned. But from a human perspective, you’d imagine that if two functions have the same name they are somehow related, even if they have a different number of parameters. For that reason, don’t use the same name for two functions that do unrelated things.