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:
#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
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:
If you need to do ...