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

Christian Maeder maeder at tzi.de
Wed Aug 16 09:22:19 EDT 2006


You might use the Prelude function until:
  until :: (a -> Bool) -> (a -> a) -> a -> a 	

  until (> 3) (+ 2) 0 = 4

or for your purpose:
   until (\ a -> not (goOn(a, f(a))) f ainit

http://www.haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v%3Auntil
http://www.haskell.org/onlinereport/prelude-index.html
http://www.haskell.org/onlinereport/standard-prelude.html#$vuntil

HTH Christian

Tamas K Papp schrieb:
> Hi,
> 
> I am a newbie learning Haskell.  I have used languages with functional
> features before (R, Scheme) but not purely functional ones without
> side-effects.
> 
> Most of the programming I do is numerical (I am an economist).  I
> would like to know how to implement the iterative algorithm below in
> Haskell.
> 
> 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.
> 
> Thank you,
> 
> Tamas


More information about the Haskell-Cafe mailing list