[Haskell-cafe] Newbie and working with IO Int and Int

Robert Dockins robdockins at fastmail.fm
Tue Oct 17 13:44:38 EDT 2006


On Oct 17, 2006, at 1:37 PM, Víctor A. Rodríguez wrote:

>> What's wrong with doing it this way?
>>
>> -- ** UNTESTED CODE **
>>
>> verifyAdd :: Int -> Int -> Int -> Bool
>> verifyAdd a b sum | a + b == sum = True
>> otherwise = False
>>
>> testAddMundane :: Int -> Int -> Bool
>> testAddMundane a b = verifyAdd a b (a + b)
>>
>> -- all the IO-dependent stuff is below this line --
>>
>> testAddRandom :: IO Bool
>> testAddRandom = do a <- randomIO
>> b <- randomIO
>> return verifyAdd a b (a + b)
>>
> I discovered something worst yet :-P
> Using the next code and calling verifyAdd or testAddMundane it says :
>
> Program error: verifyAdd: ERROR
>
> Instead calling testAddRandom only says :
>
> :: IO Bool
> (55 reductions, 92 cells)

This is due to the magic of lazy evaluation.  You never use the  
result of 'testAddRandom', so it's never evaluated, which means your  
call to 'error' is also never evaluated.

Type:

testAddRandom >>= print

on the command line and you should get the same error, because the  
call to 'print' demands the result of running testAddRandom.


> ---- CODE STARTS HERE, AND IS TESTED -----
>
> import Random
>
> verifyAdd :: Int -> Int -> Int -> Bool
> verifyAdd a b sum = error "verifyAdd: ERROR"
>
> testAddMundane :: Int -> Int -> Bool
> testAddMundane a b = verifyAdd a b (a + b)
>
> -- all the IO-dependent stuff is below this line --
>
> testAddRandom :: IO Bool
> testAddRandom = do a <- randomIO
> b <- randomIO
> return ( verifyAdd a b (a+b) )
>
> --
> Víctor A. Rodríguez (http://www.bit-man.com.ar)
> El bit Fantasma (Bit-Man)
> Perl Mongers Capital Federal (http://cafe.pm.org/)
> GNU/Linux User Group - FCEyN - UBA (http://glugcen.dc.uba.ar/)
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe


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