[Haskell-beginners] How to display a time difference?

Sean Lee sean.ysl at gmail.com
Wed Mar 18 06:35:50 EDT 2009


Hi Colin

The following code probably would do what I wanted to do.

play_move :: IORef Game_state -> IO ()
play_move game_state_ior = do
 (_, state, _) <- readIORef game_state_ior
 putStr "Playing AI: "
 start_time <- getCurrentTime
 let move = recommended_move state
 end_time <- move `seq` (modifyIORef game_state_ior $!
update_interactive_from_move move) `seq` getCurrentTime
 putStrLn $ show $ (diffUTCTime end_time start_time)

Due to the non-strictness of Haskell, the evaluation of the
expressions between start_time and end_time is deferred until there is
a need.
By using `seq` and ($!), the strictness can be forced.


Sean

On Wed, Mar 18, 2009 at 9:28 PM, Colin Paul Adams
<colin at colina.demon.co.uk> wrote:
>>>>>> "Yitzchak" == Yitzchak Gale <gale at sefer.org> writes:
>
>    Yitzchak> Colin Paul Adams wrote:
>    >> The code of the following routine is intended to indicate how
>    >> long it takes for the computer to make a move. However the time
>    >> is printed (as very close to zero) long before the move is
>    >> made.
>
>    Yitzchak> You are writing a thunk to the IORef. It only gets
>    Yitzchak> computed later on when you read the value.
>
>    Yitzchak> Try using:
>
>    >> readIORef game_state_ior >>= evaluate
>    >> . update_interactive_from_move move >>= writeIORef
>    >> game_state_ior
>
>    Yitzchak> evaluate is in Control.Exception.
>
> Still no joy with:
>
> play_move :: IORef Game_state -> IO ()
> play_move game_state_ior = do
>  (_, state, _) <- readIORef game_state_ior
>  putStr "Playing AI: "
>  start_time <- getCurrentTime
>  let move = recommended_move state
>  readIORef game_state_ior >>=
>    evaluate . update_interactive_from_move move >>=
>             writeIORef game_state_ior
>  end_time <- getCurrentTime
>  putStrLn $ show $ (diffUTCTime end_time start_time)
>
>
> --
> Colin Adams
> Preston Lancashire
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>



-- 
Sean Lee
PhD Student
Programming Language and Systems Research Group
School of Computer Science and Engineering
University of New South Wales
http://www.cse.unsw.edu.au/~seanl


More information about the Beginners mailing list