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!
Trending in Questions
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated!
To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead.
Sta...
New
Hello !
We want new/edit form pages to POST/PUT to their own URL rather than the resources REST defaults (post /things, put /things/:id)...
New
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app?
Looking for hints regarding:
Addi...
New
Hi all, I wanted to ask how the community is dealing with post-release steps.
Today we have Ecto migrations, which make sure that the db...
New
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New
Other Trending Topics
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve.
They are GUI (Emerge) and State management (S...
New
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #elixirconf-us
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #performance
- #security











Marked As Solved
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: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
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.
Last Post!
English3000
Alright, I’ll just analyze the auxiliary space complexity of each working implementation here:
Given the tree–
–insert a new value, 1, using both body and tail recursion. Determine for each the time and auxiliary space complexity of this operation.
body recursion
BodyTree.insert(tree, 1)In all, inserting into a body recursive BST could take at worst O(n(n-1)/2) auxiliary space if all nodes are along one branch and at worst O(n) time. On average, auxiliary space should be theta(n/2 * (n-1)/2) for a balanced tree and time should be theta(log 2 n).
tail recursion
TailTree.insert(tree, 1)Inserting into a tail recursive BST could take at worst O(n(n-1)/2) auxiliary space if all nodes are along one branch and at worst O(n) time. On average, auxiliary space should be theta(n/2 * (n-1)/2) for a balanced tree and time should be theta(log 2 n).
So both have the same performance, albeit the operations involved in making tail recursive calls cumulatively may take longer–copying complex data structures into each new stack frame doesn’t count as extra auxiliary space but takes longer because less is copied over in each body recursive call. This can account for body recursion being 10% faster (as mentioned in the benchmarking blog post). What accounts for tail recursion not being more space efficient is the need for the options list which effectively is explicitly managing the call stack ourselves.
Personally, I find tail recursion easier to follow because it makes each recursive step explicit (whereas with body recursion, one must reason through what will happen in one’s head). However, it does introduce significantly more complex code when applied to non-primitive and non-collective data structures and comes at a slight performance cost.
That said, if performance were really paramount, the code would be written in C (or nowadays maybe Rust or Haskell).
Personally, my takeaway is to first see if there’s a straightforward body-recursive implementation. If it seems like the body recursion will be particularly complex, I will now use the strategy @peerreynders introduced–explicitly managing the call stack myself–to reason through each step. This will initially result in a tail-recursive implementation, but hopefully doing so will allow me to identify the comparatively simpler body-recursive implementation.
I.e. I’m balancing explicitness with simplicity.