Hi,
I’m pretty sure it is the case but I found conflicting informations online.
Can you confirm that the tail call optimization will take place for a function when only the first call is wrapped in a try/catch?
For instance this module:
defmodule T do def top do until(1_000_000_000) catch e -> {:got, e} end defp until(n, n) do throw(:hello) end defp until(n, x) do until(n, x + 1) end defp until(n) do until(n, 0) end end IO.inspect(T.top())
As you can see, the first call to until
is wrapped in a try/catch
but afterwards, there are no more wrapping blocks around the recursion. So TCO should be there, right?
I’m pretty sure this example would blow up if that were not the case anyway
Other case, with this code:
defmodule T do def top do until(1_000) catch e -> {:got, e} end defp until(n, m) when m >= n do throw(:hello) end defp until(n, x) do add = try do some_other_fun() catch _ -> 1 end until(n, x + add) end defp until(n) do until(n, 0) end defp some_other_fun do case Enum.random(1..2) do 1 -> throw(:nope) 2 -> 2 end end end
The try/catch around some_other_fun
does not wrap the tail call, so TCO is still there right?
Thanks!