[Haskell-cafe] Re: Haskell code for this example of flow control
Robert Dockins
robdockins at fastmail.fm
Fri Feb 3 11:46:45 EST 2006
On Feb 3, 2006, at 11:28 AM, Maurício wrote:
> 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.
FYI, here's a thread from a few months back about monad control
structures; it may also provide some enlightenment.
http://www.haskell.org/pipermail/haskell-cafe/2005-October/011890.html
Rob Dockins
Speak softly and drive a Sherman tank.
Laugh hard; it's a long way to the bank.
-- TMBG
More information about the Haskell-Cafe
mailing list