The Root of the Problem. Part 2.

In the previous post I discussed an algorithm for calculating the square root of a number. This short post will show an implementation in Haskell.

I did one implementation using the State Monad but to be quite honest it was an impenetrable mess! I’m sure part of that was down to my embryonic Haskell skills but perhaps the State Monad was a bad fit for this problem? The implementation below uses a fold over a list of digit pairs and the start state for the fold is based on ‘the largest integer squared’ with subsequent calculations using ‘doubling’ – as per the algorithm. Most of the other functions are really helpers for formatting, digit pair extraction, decimal point location etc. I think the code is fairly readable yet I still feel it is a little too complex and would welcome any comments from more experienced Haskellers.

And some examples of using it…

and if we compose map (^2) with map root we should get back exactly what we started with in the case of perfect squares and something more or less the same for others.

Thanks for reading…!

Leave a Reply

Your email address will not be published. Required fields are marked *

ˆ Back To Top