Skip to Content
Introducing Erlang
book

Introducing Erlang

by Simon St. Laurent
January 2013
Beginner to intermediate content levelBeginner to intermediate
204 pages
4h 26m
English
O'Reilly Media, Inc.
Content preview from Introducing Erlang

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

You can create functions in the Erlang shell using 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, 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 fun, separate them with commas, like FallVelocity = fun(Distance) -> X = (2 * 9.8 * Distance), math:sqrt(X) end.

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. If you want a slightly more detailed sign that Erlang understood you, you can use the b() shell command to see what it thinks:

2> b().
FallVelocity =
    fun(Distance) ->
           math:sqrt(2 * 9.8 * Distance)
    end
ok

Conveniently, binding the function to the ...

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

Building Web Applications with Erlang

Building Web Applications with Erlang

Zachary Kessin
Études for Erlang

Études for Erlang

J. David Eisenberg
Erlang by Example with Cesarini and Thompson

Erlang by Example with Cesarini and Thompson

Simon Thompson, Francesco Cesarini
Erlang and OTP in Action

Erlang and OTP in Action

Eric Merritt, Richard Carlsson, Martin Logan

Publisher Resources

ISBN: 9781449331757Supplemental ContentErrata