Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

translate while ( x < SomeTreshold ) in haskell

Tags:

haskell

It occurs a lot when implementing algorithms that you check in every iteration of a while loop if a certain variable is smaller than a certain treshold.

In imperative languages it would look like :

 while ( x < TRESHOLD ) {
      x = usefullStuff();
 }

Where of course usefullStuff is affecting x somehow...

How do you translate this construct into haskell exploiting the functional programming paradigm?

like image 540
Jeremy Knees Avatar asked Dec 17 '25 07:12

Jeremy Knees


1 Answers

Even though I don't know what your program does, I have a feeling that you'll want to structure your logic a little differently. Have a look at section 4 of the paper Why Functional Programming Mattes - for some ideas. It deals with a similar situation involving finding the roots of an equation using Newton's method. There the responsibilities are partitioned so that the loop logic is decoupled from the generation of successive approximations.

If usefulStuff is a monad - i.e. a function with side effects, you'll have to use something like this:

whileLoop x
  | x < THRESHOLD = return x
  | otherwise     = do x <- usefulStuff
                       whileLoop x
like image 162
ErikR Avatar answered Dec 20 '25 00:12

ErikR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!