Skip to Content
Introducing Erlang, 2nd Edition
book

Introducing Erlang, 2nd Edition

by Simon St. Laurent
March 2017
Beginner
212 pages
4h 47m
English
O'Reilly Media, Inc.
Content preview from Introducing Erlang, 2nd Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Erlang Programming

Erlang Programming

Francesco Cesarini, Simon Thompson
Erlang and OTP in Action

Erlang and OTP in Action

Eric Merritt, Richard Carlsson, Martin Logan
Introducing Erlang

Introducing Erlang

Simon St. Laurent

Publisher Resources

ISBN: 9781491973363Errata PageSupplemental Content