[Haskell-beginners] Printing the result of a function evaluation
Stephen Blackheath [to Haskell-Beginners]
mutilating.cauliflowers.stephen at blacksapphire.com
Mon Mar 8 19:16:49 EST 2010
Travis,
because 'speedTest (read $ head args) `seq` return ()' is semantically
equivalent to 'return ()' whose type is IO () therefore 'v <- a' assigns
() to v.
'time (return $! speedTest (read $ head args))' is better...
however, it's still not going to do what you want (time how long it
takes speedTest to evaluate, I'm assuming), because (speedTest (read $
head args)) will only get evaluated once.
The only way to actually time how long speedTest takes is to pass a
function e.g. (Int -> IO t) to 'time', and have 'time' pass it a dummy
argument, so that GHC can't optimize the evaluation of speedTest out.
Steve
Travis Erdman wrote:
> Why oh why doesn't this work as I expect, and what is the simplest fix?
>
> speedTest 4 = 44
>
> time :: (Show t) => IO t -> IO t
> time a = do
> start <- getCPUTime
> v <- a
> end <- getCPUTime
> let diff = (fromIntegral (end - start)) / (10^12)
> print v -- WHY DOESNT THIS WORK? ALWAYS PRINTS () ....
> printf "Computation time: %0.3f sec\n" (diff :: Double)
> return v
>
> main :: IO ()
> main = do
> args <- getArgs
> time $ speedTest (read $ head args) `seq` return ()
>
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
More information about the Beginners
mailing list