是否可以在等待几秒钟后调用 Scheme 中的过程?
例如:
(define (facs)
(fac 3)
;wait 5 seconds
(fac 7))
答案 0 :(得分:2)
标准方案中没有规定睡眠程序;您将需要依赖特定于实现的功能。
如果您使用的是 Guile Scheme,则可以使用 sleep
休眠数秒,或使用 usleep
休眠数微秒:
(define (delayed-5s msg)
(display "Waiting 5s...")
(force-output)
(sleep 5)
(newline)
(display msg)
(newline))
请注意,您应该刷新输出以确保在您希望看到消息时看到它们。通常,(但不总是)打印换行符会刷新输出缓冲区,因此您可以将 (newline)
移动到 (sleep 5)
之前并合理地期望显示会按预期工作;但最好显式刷新输出,以确保消息在您需要时从输出缓冲区中刷新。在上面的代码中,force-output
和 sleep
都是 Guile 特定的过程。
如果您使用的是 Chez Scheme,您可以这样做:
(define (delayed-5s msg)
(display "Waiting 5s...")
(flush-output-port (current-output-port))
(sleep (make-time 'time-duration 0 5))
(newline)
(display msg)
(newline))
在 Chez Scheme 中,sleep
接受一个 time 对象,而 make-time
接受三个参数,返回一个 time 对象。第一个是时间类型参数,第二个是纳秒数,第三个是秒数。同样,您应该刷新输出缓冲区,flush-output-port
会这样做,但它需要一个 输出端口,过程 current-output-port
提供了该端口。在上面的代码中,sleep
和 make-time
是 Chez 特定的过程,而 flush-output-port
和 current-output-port
是标准的 R6RS Scheme 库过程。
您可以看到,使用 Chez Scheme 提供的睡眠工具比 Guile Scheme 提供的睡眠工具要复杂一些。其他实现可能有类似的规定,但不是必需的。
答案 1 :(得分:1)
据我所知,不在可移植方案中。当然,许多实现都有这样做的方法。例如在球拍中:
(define (sleepy s)
(values (current-seconds)
(begin
(sleep s)
(current-seconds))))
> (sleepy 2)
1612809817
1612809819
(当然,current-seconds
也不是标准 Scheme 的一部分。)