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