Kafftum

Kafftum

Are recursive closures tail call optimized?

Would this code be tail call optimized?

  def loop do
    inner = fn func, idx, propulsor ->
              if idx === 1000 do
                propulsor + 1
              else
                :timer.sleep(1000)
                func.(func, idx + 1, propulsor)
              end
            end

    outer = fn func, idx ->
              # This should approximately turn out to be 24 hours
              if idx === 96 do
                IO.puts("Updating Cache")
                InstagramApi.main()
                func.(func, 0)
              else
                # Generates new index after a timeout of 1000 seconds
                new_idx = inner.(inner, 0, idx)

                func.(func, new_idx)
              end
            end

    outer.(outer, 0)
  end

Marked As Solved

al2o3cr

al2o3cr

It does not seem to get optimized, based on the following steps.

Start with a file bleh.ex:

defmodule InstagramApi do
  def main do
    IO.puts("Instagram API")
  end
end

defmodule Bleh do
  @compile :S

  def loop do
    inner = fn func, idx, propulsor ->
              if idx === 1000 do
                propulsor + 1
              else
                :timer.sleep(1000)
                func.(func, idx + 1, propulsor)
              end
            end

    outer = fn func, idx ->
              # This should approximately turn out to be 24 hours
              if idx === 96 do
                IO.puts("Updating Cache")
                InstagramApi.main()
                func.(func, 0)
              else
                # Generates new index after a timeout of 1000 seconds
                new_idx = inner.(inner, 0, idx)

                func.(func, new_idx)
              end
            end

    outer.(outer, 0)
  end

  def named_loop(idx \\ 0) do
    if idx === 96 do
      IO.puts("Updating Cache")
      InstagramApi.main()
      named_loop(0)
    else
      new_idx = named_inner(0, idx)

      named_loop(new_idx)
    end
  end

  def named_inner(idx, propulsor) do
    if idx === 1000 do
      propulsor + 1
    else
      :timer.sleep(1000)
      named_inner(idx + 1, propulsor)
    end
  end
end

Compile it with elixir bleh.ex. It will print an error message:

** (CompileError) bleh.ex: could not compile module Bleh. We expected the compiler to return a .beam binary but got something else. This usually happens because ERL_COMPILER_OPTIONS or @compile was set to change the compilation outcome in a way that is incompatible with Elixir

That’s expected, because the @compile :S flag causes the compiler to dump a BEAM-assembly file at bleh.ex.S and stop.

There’s a lot of detail that’s not directly relevant in the assembly; see the BEAM Book for more info. The important thing to look for is the definitions of the functions.

The closures for outer and inner are compiled to functions named -loop/0-fun-1- and -loop/0-fun-0- respectively; you can check by looking at the func_info line that shows where they came from in the source.

inner is the shorter of the two:

{function, '-loop/0-fun-0-', 3, 28}.
  {label,27}.
    {line,[{location,"bleh.ex",11}]}.
    {func_info,{atom,'Elixir.Bleh'},{atom,'-loop/0-fun-0-'},3}.
  {label,28}.
    {test,is_eq_exact,{f,29},[{x,1},{integer,1000}]}.
    {line,[{location,"bleh.ex",13}]}.
    {gc_bif,'+',{f,0},3,[{x,2},{integer,1}],{x,0}}.
    return.
  {label,29}.
    {allocate,3,3}.
    {move,{x,0},{y,0}}.
    {move,{x,1},{y,1}}.
    {move,{x,2},{y,2}}.
    {move,{integer,1000},{x,0}}.
    {line,[{location,"bleh.ex",15}]}.
    {call_ext,1,{extfunc,timer,sleep,1}}.
    {line,[{location,"bleh.ex",16}]}.
    {gc_bif,'+',{f,0},0,[{y,1},{integer,1}],{x,1}}.
    {move,{y,0},{x,3}}.
    {move,{y,2},{x,2}}.
    {move,{y,0},{x,0}}.
    {call_fun,3}.
    {deallocate,3}.
    return.

The signal that it’s not tail-call optimized is the call_fun / deallocate / return sequence.

For comparison, named_inner does the same thing but gets different optimization:

{function, named_inner, 2, 13}.
  {label,12}.
    {line,[{location,"bleh.ex",49}]}.
    {func_info,{atom,'Elixir.Bleh'},{atom,named_inner},2}.
  {label,13}.
    {test,is_eq_exact,{f,14},[{x,0},{integer,1000}]}.
    {line,[{location,"bleh.ex",51}]}.
    {gc_bif,'+',{f,0},2,[{x,1},{integer,1}],{x,0}}.
    return.
  {label,14}.
    {allocate,2,2}.
    {move,{x,1},{y,0}}.
    {move,{x,0},{y,1}}.
    {move,{integer,1000},{x,0}}.
    {line,[{location,"bleh.ex",53}]}.
    {call_ext,1,{extfunc,timer,sleep,1}}.
    {line,[{location,"bleh.ex",54}]}.
    {gc_bif,'+',{f,0},0,[{y,1},{integer,1}],{x,0}}.
    {move,{y,0},{x,1}}.
    {call_last,2,{f,13},2}. % named_inner/2

The assembly instead ends with a call_last (which also does a deallocate) and no return at all.

Where Next?

Popular in Questions Top

Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
AstonJ
You’re a programmer, so you don’t need spoon feeding with the conventional drivel about “this is an integer.” No. You need to know what’s...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New

We're in Beta

About us Mission Statement