Search code examples
haskellwaitpausepure-function

Can I make a pure Haskell function wait for 2 seconds?


In a Haskell program which I don't understand that well (yet), I would like a function

myInfo :: Int -> Picture
myInfo mode =
   ...

to take always 2 seconds longer than normal (to slow down the output).

I looked up Control.Concurrent.threadDelay, but due to its signature threadDelay :: Int -> IO () I cannot figure how to put it in the pure part of the program where the function myInfo is defined.

Is it possible to slow myInfo down (by say 2 secs) without taking the function into the impure area of the Haskell program?

The solution does not need to be production-performant. (It is only a temporary measure to understand the automatic run of the program better.)


Solution

  • Sort of – if this is for debugging you can have it as

    myInfo mode = unsafePerformIO $ do
      threadDelay 2000000
      return $ actualImplementationOfMyInfo mode
    

    However, while this may be occasionally useful for debugging / testing behaviour with degraded performance, keep in mind that GHC assumes functions are referentially transparent, so you can not rely on this behaviour.

    For instance, if you have something like

    mode = SomeMode
    ...
    
    f (myInfo mode)
    
    ...
    
    g (myInfo mode)
    

    GHC may well decide that since the two calls to myInfo are identical to only evaluate it once and reuse the result later. If you need predictable time based / sequential behaviour you're not going to get around having to get your logic into IO, one way or another.