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

Chris Kuklewicz haskell at list.mightyreason.com
Thu Feb 2 12:19:04 EST 2006


Maurício 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
> };
> 

A close to line-for-line translation:

import Data.IORef
import Control.Monad(liftM2,when)

main = example 1000

example :: Double -> IO ()
example originalA = do
  refA <- newIORef originalA  -- allocate local variable a
  refB <- newIORef 0          -- allocate local variable b
  let loop = do               -- loop in scope of refA, refB
        flag <- liftM2 (/=) (readIORef refA) (readIORef refB)
        when flag $ do
          modifyIORef refA (/2)
          print =<< readIORef refA
          -- This will give an error if not a number:
          writeIORef refB =<< readIO =<< getLine
          loop
  loop -- start executing loop



More information about the Haskell-Cafe mailing list