A Word About Tail Recursion
Take a look at the receive loop in the area server that we wrote earlier:
area_server_final.erl | |
| loop() -> |
| receive |
| {From, {rectangle, Width, Ht}} -> |
| From ! {self(), Width * Ht}, |
| loop(); |
| {From, {circle, R}} -> |
| From ! {self(), 3.14159 * R * R}, |
| loop(); |
| {From, Other} -> |
| From ! {self(), {error,Other}}, |
| loop() |
| end. |
If you look carefully, you’ll see that every time we receive a
message, we process the message and then immediately call
loop()
again. Such a procedure is called
tail-recursive. A tail-recursive function can be compiled so that the last function call in a sequence of statements can be replaced by a simple jump to the start of the function being called. This means that a tail-recursive ...
Get Programming 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.