This is tail recursion.

I have the following code snippet:

def flatten([h|t]), do: [h] ++ flatten(t)

I'm pretty new in the fp world and want to know if this is tail recursion?

+4
source share
1 answer

This is not tail recursion. In order for the last expression ( ++, list concatenation) to be performed , it [h]must be supported, and a new call flatten(t)will lead to the creation of a new stack frame and cannot simply replace the previous one due to the link to [h].

In other words, when optimizing the tail call, calling the top-level function replaces the previous stack. Any expressions inside this function call are executed before the hand and will increase the stack when they are called.

, ( ), . @GavinBrelstaff, :

defmodule RC do
  def flatten(list, acc \\ [])
  def flatten([], acc), do: Enum.reverse(acc)
  def flatten([h|t], acc) when is_list(h), do: flatten(h++t, acc)
  def flatten([h|t], acc), do: flatten(t, [h|acc])
end

bodyless [] . , , , . , Enum.reverse VM.

+8

Source: https://habr.com/ru/post/1627690/


All Articles