Recursive Functions using a Trampoline in Clojure
Following on from yesterdays post that discussed ‘Trampolining’ in JavaScript, I thought it would be interesting to see what Clojure has to offer.
Following on from yesterdays post that discussed ‘Trampolining’ in JavaScript, I thought it would be interesting to see what Clojure has to offer.
An interesting technique for managing perceived tail-call optimised algorithms in an environment that does not provide such capabilities is to use a concept called a ‘trampoline’. The following two examples provide all their work within the recursive function invocation and are in tail-call position. However in environments without such optimisations (before ES2015), a single stack-frame is not reused and instead has the pain of O(n) memory complexity.
Whilst currently reading through The Joy of Clojure book I was introduced to the concept of pre and post-conditionals, similar to another language I have heard about called Eiffel. To experiment with this feature I decided to create a simple merge-sort algorithm implementation which provided the post invariant that its returned values were sorted by the provided predicate.
Following on from my previous post, I have continued my exploration into Clojure by implementing a simple infix calculator - using the Shunting Yard algorithm and RPN evaluation. The documented implementation is split into three distinct parts of which I will describe piece-by-piece, before composing them together to result in the final calculator.
This past Christmas break I had the chance to finally pick up The Joy of Clojure book and delve into the world of Lisp. Along with the common-place Merge-sort algorithm I find it beneficial to explore a new language and its capabilities by solving the FizzBizz code kata. In this post I will be explaining a couple of the implementations that I created.