R
R
rusikus2019-10-24 03:08:37
Erlang
rusikus, 2019-10-24 03:08:37

Recursive function in practice?

Please explain the essence of recursion and tail recursion in Erlang. Only not on the example of calculating the factorial, but for example on hares. That is, a practical example.
I will add. If you can give a simple example (you can link) of a practical recursive function that considers the same hares with comments and the same function with tail recursion.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2019-10-24
@rusikus

In general, recursion is when a function calls itself.
Let's take fibonacci numbers: f(x)=f(x-1)+f(x-2), f(0) = 1, f(1) = 1
Erlang code:
```
f(0) -> 1;
f(1) -> 1;
f(X) -> f(X-1)+f(X-2).
```
This is a general recursion, it cannot be optimized because the result of execution depends on the result of execution of the same function with different arguments. But the given result depends on something else, so the recursion cannot be optimized (non-tail).
Any loop:
```
for i=10 to 1:
do_something
```
loop(0) -> ok;
loop(N) ->
do_something,
loop(N-1).
```
In this case, the recursion is called tail, because the result of the current function execution is completely the result of the function execution for the next iteration. Those. in this case, the compiler/interpreter may not care. to keep track of which function the current function was called from. It simply remembers the entry point to this recursion, and now knows that the result of the very first call will be the result of the very last one.
Those. in other words, calling loop(3) would be equivalent to:
```
loop(3),
loop(2),
loop(1),
ok.
```
is just plain linear code, not recursive in the general sense of the word.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question