Chapter 2. Functions and Modules

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

Fun with fun

Erlang provides a tool for creating functions in the shell, the appropriately named fun. For example, to create a function that calculates the velocity of a falling object based on the distance it drops in meters, you could create the following:

1> FallVelocity = fun(Distance) -> math:sqrt(2 * 9.8 * Distance) end.
#Fun<erl_eval.6.111823515>

You can read that as a pattern match that binds the variable FallVelocity to a function that takes an argument of Distance. 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 squared, times Distance (in meters). Then the function comes to an end, and a period closes the statement.

Note

If you want to include multiple statements in a function defined by a fun, separate them with commas, like FallVelocity = fun(Distance) -> X = (2 * 9.8 * Distance), math:sqrt(X) end. You can read the commas as and.

The return value in the shell, #Fun<erl_eval.6.111823515>, isn’t especially meaningful by itself, but it tells you that you’ve created a function and didn’t just get an error. The number in the return value will probably be different. If you want a slightly more detailed sign that Erlang understood you, you can use the b() shell command ...

Get Introducing Erlang, 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.