17

This really shouldn't be so difficult to find an answer to, but alas I don't... I want to delay the next execution step in a do block. I have found the functions delay, sleep, nanosleep and usleep.

And also this question, that doesn't cover how to use any of these, however: Sleep in Haskell.

I am getting the same error for all of these, so probably I am doing something wrong fundamentally:

Variable not in scope: delay :: Integer -> IO a0

This is my test snippet:

main = do
  {
    putStrLn "line 1"
  ; delay 2
  ; putStrLn "line 2"
  }

Googling the error does not actually yield anything useful for some reason.

Chris Stryczynski
  • 30,145
  • 48
  • 175
  • 286
lo tolmencre
  • 3,804
  • 3
  • 30
  • 60

1 Answers1

31

Well, you have to import Control.Concurrent first:

import Control.Concurrent

threadDelay 1000000 --sleep for a million microseconds, or one second
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • 1
    Ok, not very useful error message. I would expect something like `unknown symbol "delay"`... in fact, it does seem to know the symbol, as it knowns the function's signature. So then why do I need to import the definition? And also... what would I need to import to use that actual `delay` function rather than `threadDelay`? – lo tolmencre Dec 14 '17 at 15:04
  • 10
    It knows the type because of _type inference_. The function with the _required_ signature doesn't exist, though, so you get an error message. Then, the `delay` function is non-standard, and you need to install a 3rd party package called `concurrent-extra`, as the link suggests. Then you `import Control.Concurrent.Thread.Delay`, and that's it. I'm not sure why you need that specific function since `threadDelay` is the standard way to suspend program execution in Haskell. – ForceBru Dec 14 '17 at 15:08
  • @ForceBru When I first started looking for a delay function, the first search term which came up was this extra package, and I mistakenly used that for a while before realising there was a version in Control.Concurrent. So possibly just search engines turning up the wrong thing. – Zpalmtree Dec 14 '17 at 16:36