English3000

English3000

Is it possible to build up data structures tail-recursively?

For context, check out this blog post.

To summarize, I tried building a BST using tail-recursion only to realize that when children are modified, their parent node’s reference will point to the older version.

While body-recursion allows for very simple generators, it comes at the cost of greater call stack usage. As a result, a tail-call optimized solution would reduce auxiliary space complexity. But given the immutability of data in Elixir, I’m wondering whether such an optimization is possible–and if so, some examples would be much appreciated!

Thanks!

Marked As Solved

peerreynders

peerreynders

When converting from body recursion to tail recursion you essentially are taking responsibility for managing “your own data stack”. In most functional programming languages the head of a list can be added or removed fairly cheaply - making lists excellent stacks.

Furthermore the BEAM performs “last call optimization”. To some, “tail call optimization” may imply recursive calls within the same function. The BEAM doesn’t allocate a new stack frame even when one function’s “tail call” invokes an entirely different function. So mutual recursion can also be optimized.

With a Tree, last call optimization might look like this:

defmodule Tree do
  defstruct value: nil, left: :leaf, right: :leaf

  def new,
    do: :leaf

  def new(value),
    do: %Tree{value: value}

  def insert(tree, value),
    do: insert(tree, value, [])

  defp insert(:leaf, value, ops) do
    insert_ops(new(value), ops)
  end
  defp insert(%Tree{value: value, left: left, right: right} = tree, new_value, ops) do
    cond do
      value < new_value ->
        insert(right, new_value, [{:right, tree} | ops])
      true ->
        insert(left, new_value, [{:left, tree} | ops])
    end
  end

  defp insert_ops(tree, []),
    do: tree
  defp insert_ops(subtree, [{side, tree} | rest]),
    do: insert_ops(Map.put(tree, side, subtree), rest)

  def traverse(tree, acc, fun),
    do: traverse(tree, acc, fun, [])

  defp traverse(:leaf, acc, _fun, []),
    do: acc
  defp traverse(:leaf, acc, fun, [{right,value} | rest]),
    do: traverse(right, fun.(value, acc), fun, rest)
  defp traverse(%Tree{value: value, left: left, right: right}, acc, fun, ops),
    do: traverse(left, acc, fun, [{right, value} | ops])

  def to_list(tree),
    do: :lists.reverse(Tree.traverse(tree, [], &([&1|&2])))

  def from_enum(enum),
    do: Enum.reduce(enum, Tree.new(), &(Tree.insert(&2,&1)))

end

show = fn tree ->
  IO.inspect(tree)
  IO.inspect(Tree.to_list(tree))
end
show_from_enum = fn enum ->
  show.(Tree.from_enum(enum))
end

show.(Tree.new())
show.(Tree.new(1))
show_from_enum.([])
show_from_enum.([1])
show_from_enum.(1..9)
show_from_enum.(9..1)
show_from_enum.([8,4,12,2,6,10,14,1,3,5,7,9,11,13,15])

Allocating a stack frame is likely a highly optimized BEAM level operation and the memory cost related to how much data is captured in the frame. With tail calls you can be very exact what data needs to be captured but there is some overhead (in complexity and reductions) to explicitly managing that captured data. So the tradeoffs will depend a lot on the details of the particular use case.

Also Liked

ericmj

ericmj

Elixir Core Team

Is the optimization necessary and is it really an optimization? Recursing a 100 times on a function with a reasonable stack size is no problem in Elixir, this means you can do operations on a BST with 2^100 elements without much cost.

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
Fl4m3Ph03n1x
Background Let’s assume I have a typical GenServer that receives messages as requests, does some operation in a DB and returns responses....
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

Other popular topics Top

albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
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
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
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

We're in Beta

About us Mission Statement