首页 > 解决方案 > 等待几秒钟后调用Scheme中的过程?

问题描述

等待几秒钟后是否可以在 Scheme 中调用一个过程?

例如:

(define (facs)
(fac 3)
;wait 5 seconds
(fac 7))

标签: schemelisp

解决方案


标准方案中没有睡眠程序的规定;您将需要依赖特定于实现的功能。

如果您使用的是 Guile Scheme,您可以使用sleepto sleep for a number of seconds 或usleepto sleep for a number of microseconds:

(define (delayed-5s msg)
  (display "Waiting 5s...")
  (force-output)
  (sleep 5)
  (newline)
  (display msg)
  (newline))

请注意,您应该刷新输出以确保在您希望看到消息时看到消息。通常,(但并非总是)打印换行符会刷新输出缓冲区,因此您可以提前移动(newline)(sleep 5)合理地期望显示将按预期工作;但最好是显式刷新输出,以确保消息在您需要时从输出缓冲区中刷新。在上面的代码中,force-outputsleep都是 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接受一个时间对象,并make-time接受三个参数,返回一个时间对象。其中第一个是时间类型参数,第二个是纳秒数,第三个是秒数。同样,您应该刷新输出缓冲区,并flush-output-port执行此操作,但它需要过程提供的output-portcurrent-output-port。在上面的代码中,sleepmake-time是 Chez 特定的程序,但是flush-output-portcurrent-output-port是标准的 R6RS Scheme 库程序。

你可以看到,使用 Chez Scheme 提供的 sleep 工具比 Guile Scheme 提供的要复杂一些。其他实现可能有类似的规定,但不是必须的。


推荐阅读