Chapter 2. Functions and Modules

Like most programming languages, Elixir lets you define functions to help you represent repeated calculations. While Elixir functions can become complicated, they start out reasonably simple.

Fun with fn

You can create functions in IEx using the keyword fn. For example, to create a function that calculates the velocity of a falling object based on the distance it drops in meters, you could do the following:

iex(1)> fall_velocity = fn (distance) -> :math.sqrt(2 * 9.8 * distance) end
#Function<6.6.111823515/1 in :erl_eval.expr/5>

That binds the variable fall_velocity to a function that takes an argument of distance. (Parentheses are optional around the argument.) The function returns (I like to read the -> as “yields”) the square root of 2 times a gravitational constant for Earth of 9.8 m/s, times distance (in meters). Then the function comes to an end.

The return value in the shell, #Function<6.6.111823515/1 in :erl_eval.expr/5>, isn’t especially meaningful by itself, but it tells you that you’ve created a function and didn’t just get an error. (The exact format of that return value changes with Elixir versions, so it may look a bit different.)

Conveniently, binding the function to the variable fall_velocity lets you use that variable to calculate the velocity of objects falling to Earth:

iex(2)> fall_velocity.(20)
iex(3)> fall_velocity.(200)
iex(4)> fall_velocity.(2000)

If you need to do ...

Get Introducing Elixir now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.