[Haskell-cafe] iterative algorithms: how to do it in Haskell?

Antti-Juhani Kaijanaho antti-juhani at kaijanaho.fi
Wed Aug 16 09:39:33 EDT 2006


Tamas K Papp wrote:
> f is an a->a function, and there is a stopping rule 
> goOn(a,anext) :: a a -> Bool which determines when to stop.  The
> algorithm looks like this (in imperative pseudocode):
> 
> a = ainit
> 
> while (true) {
>       anext <- f(a)
>       if (goOn(a,anext))
>       	 a <- anext
>       else
>          stop and return anext
> }
> 
> For example, f can be a contraction mapping and goOn a test based on
> the metric.  I don't know how to do this in a purely functional
> language, especially if the object a is large and I would like it to
> be garbage collected if the iteration goes on.

The idea is to make the iteration variables arguments to a
tail-recursive function:

let foo a | goOn a anext = foo anext
          | otherwise    = anext
    where anext = f a
in foo ainit




More information about the Haskell-Cafe mailing list