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 (we like to read the -> as “yields”) the square root of 2 times a gravitational constant for Earth of 9.8 m/s2, 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)
19.79898987322333
iex(3)> fall_velocity.(200)
62.609903369994115
iex(4)> fall_velocity.(2000)
197.9898987322333

If you need to ...

Get Introducing Elixir, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.