[Haskell-cafe] Re: Haskell code for this example of flow control

Maurício briqueabraque at yahoo.com
Fri Feb 3 11:28:16 EST 2006


Kurt Hutchinson wrote:
> On 2/2/06, Maurício <briqueabraque at yahoo.com> wrote:
> 
>>   I understand those examples, but I really would like to know how to
>>do that with monads. I would like to ask the same question, but now with
>>this code:
>>
>>double a = 1000;
>>double b = 0;
>>while (a != b) {
>>     a /= 2;
>>     cout << a; // Prints a
>>     cin << b; // User gives a number, stored in b
>>};
> 
> 
> An idiomatic approach:
> example :: Double -> Double -> IO ()
> example a b
>     | a == b    = return ()
>     | otherwise = do
>         let a' = a / 2
>         print a'
>         b' <- readLn
>         example a' b'
> 
> main = example 1000 0

   Thanks! Robert's, Chris' and yours examples solved many of my 
questions. I understand I can insert modifications in IORefs (as used by 
Robert and Chris) inside the loop above:

| otherwise = do
      let a' = a / 2
      ...
      modifyIORef some_ioref some_function
      ...
      example a' b'

   I wonder if I could write a generic while based on your example:

while :: (a -> IO a) -> (a -> Bool) -> IO ()

   I'll probably learn something trying that.

   Best,
   Maurício



More information about the Haskell-Cafe mailing list