Reputation: 47
Is it possible to call a procedure in Scheme after waiting a few seconds?
For example:
(define (facs)
(fac 3)
;wait 5 seconds
(fac 7))
Upvotes: 0
Views: 396
Reputation:
Not in portable Scheme as far as I know. Many implementations will have ways of doing this, of course. For instance in Racket:
(define (sleepy s)
(values (current-seconds)
(begin
(sleep s)
(current-seconds))))
> (sleepy 2)
1612809817
1612809819
(Of course, current-seconds
is also not part of standard Scheme.)
Upvotes: 1
Reputation: 21367
There is no provision for a sleep procedure in Standard Scheme; you will need to rely on implementation-specific features.
If you are using Guile Scheme, you can use sleep
to sleep for a number of seconds, or usleep
to sleep for a number of microseconds:
(define (delayed-5s msg)
(display "Waiting 5s...")
(force-output)
(sleep 5)
(newline)
(display msg)
(newline))
Note that you should flush the output to be sure that messages are seen when you want them seen. Typically, (but not always) printing a newline will flush the output buffer, so you could move (newline)
before (sleep 5)
and reasonably expect that the display will work as expected; but it is better to flush the output explicitly to ensure that messages are flushed from the output buffer when you want them to be. In the above code, both force-output
and sleep
are Guile-specific procedures.
If you are using Chez Scheme, you can do this:
(define (delayed-5s msg)
(display "Waiting 5s...")
(flush-output-port (current-output-port))
(sleep (make-time 'time-duration 0 5))
(newline)
(display msg)
(newline))
In Chez Scheme, sleep
takes a time object, and make-time
takes three arguments, returning a time object. The first of those is a time-type argument, the second is the number of nanoseconds, and the third is the number of seconds. Again, you should flush the output buffer, and flush-output-port
does that, but it needs an output-port, which the procedure current-output-port
provides. In the above code, sleep
and make-time
are Chez-specific procedures, but flush-output-port
and current-output-port
are standard R6RS Scheme library procedures.
You can see that using the sleep facility provided by Chez Scheme is a little bit more involved than the one provided by Guile Scheme. Other implementations are likely to have similar provisions, but they are not required to.
Upvotes: 2