【发布时间】:2011-03-03 02:04:52
【问题描述】:
我无法理解 delay 宏在 Clojure 中的工作原理。它似乎没有做预期的事情(即:延迟评估)。正如您在此代码示例中看到的:
; returns the current time
(defn get-timestamp [] (System/currentTimeMillis))
; var should contain the current timestamp after calling "force"
(def current-time (delay (get-timestamp)))
但是,在 REPL 中调用 current-time 似乎会立即计算表达式,即使没有使用 force 宏:
user=> current-time
#<Delay@19b5217: 1276376485859>
user=> (force current-time)
1276376485859
为什么get-timestamp 的评估没有延迟到第一次force 调用?
【问题讨论】:
-
次要评论:最好直接使用 (System/currentTimeMillis) 而不是构造 Date - 它们使用相同的底层毫秒源,但前者避免了不必要的对象分配。
标签: clojure delay lazy-evaluation