[Haskell-cafe] Application of iterate

Logesh Pillay logesh at iafrica.com
Fri Mar 23 07:04:47 EDT 2007

Ordinarily I would not post to a list when I've got a program running.  

But I've found learning Haskell so tough (this is my 4th try in the last
two years) that I feel I have to bore everyone with my first non-trivial
program.  It is Newton's  method adapted to give the square root of a
number.  And all in just one line which I think is an amazing
demonstration of the power of Haskell.  And it took no more than a
couple of minutes to write (directly to the screen too as opposed to the
usual many paper drafts with C).  It works too, correct to 13 decimal
points on my GHC system

It is :-

my_sqrt t = last (take 20 (iterate (\n -> n/2 + t/(2 * n)) t))

It is a bit crude though.  20 iterations is a bit arbitrary. I don't suppose
there is a easy way to iterate until the results stop changing.

More information about the Haskell-Cafe mailing list