Functional programming and root finding

I recently discovered Incanter which looks really promising for statistical computing on the JVM. Incanter is written in Clojure, a lisp like functional programming language for the JVM. We have been using Scala, a hybrid OO/functional programming language for the JVM, in one of our applications but I have yet to find a robust statistics API for Scala. We also use R in the same application. It would be nice to stay within the JVM for statistical procedures rather than communicate between the JVM and an R session.

I wanted to investigate Incanter, but first I needed to wrap my head around Clojure. Folding and nesting are common procedures in functional programming languages and in numerical methods. Many algorithms follow the iterate and accumulate procedure that naturally maps to the folding and nesting paradigms. Newton’s Method for polynomial root finding follows this paradigm as do many optimization algorithms that converge on an extrema. As an avid Mathematica enthusiast, I often used NestList to implement and visualize the steps of nesting algorithms, but I haven’t found the equivalent built into the libraries of any of the other three languages. So, to dive in to Clojure and Incanter, I decided to implement the root finding in Clojure, Scala, and R for comparison. First, we need a NestList equivalent. Then, we can use the NestList function to implement the root finding algorithm which we’ll test out on the trivial polynomial x^2-5 which obviously has its root at ~±2.23606797749979.

The root finding algorithm using NestList in Mathematica can be viewed here.

The iterate function is exactly what I was looking for. The lazy evaluation of the sequence makes it easy to work with and the definition of the nestlist function is just syntactic sugar on the iterate function.

In Scala, the implementation of nestlist uses the foldLeft function and accumulates its results