You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In tail call recursive version, an accumulator sum is used to pass the current state of the function's execution. When the base case is reached, the accumulator is used to return the final value of the recursive function call.
Note: Not at all programming languages support tail call optimization. Python, Javascript don't support. Ruby allows you to optionally enable it, even though it’s not the default.
1. Loop over the list
Due to immutability, loops in Elixir are written differently from imperative languages. For example, loops commonly look like:
In a functional language, mutating i (by calling i++) is not possible. Thus, Elixir uses recursion for looping over data structures like lists.
The equivalent of a for loop in Elixir would look like this:
Example: sum all integer of the list
2. Tail Call Recursion
Because Elixir implements tail call optimization, so we can use tail call recursion to reduce the number of stack frames.
We will rewrite
sum_numbers
function in example 1 using tail call recursive version.In tail call recursive version, an accumulator
sum
is used to pass the current state of the function's execution. When the base case is reached, the accumulator is used to return the final value of the recursive function call.Note: Not at all programming languages support tail call optimization. Python, Javascript don't support. Ruby allows you to optionally enable it, even though it’s not the default.
View more about Tail Call Optimization in elixir: https://dino.codes/posts/tail-call-optimization-in-elixir/
The text was updated successfully, but these errors were encountered: