首页 > 解决方案 > Clojure. Intellij. Delay. Concurrent. Clojure from the Ground Up

问题描述

I'm trying to solve the Exercises at the end of Chapter 6 of Clojure From the Ground Up. Here's what happens to me on the Very First Problem there...

  (defn sum [start end] (delay (reduce + (range start end))))  ;; Define sum.
=> #'chapter6.core/sum

  (time (sum 0 1e7))  ;; Start sum but it delays, so almost no time elapses.
"Elapsed time: 0.2808 msecs"
=> #object[clojure.lang.Delay 0x2656db01 {:status :pending, :val nil}]

  (deref sum)  ;; Ask for the result. This should take some time. Only it doesn't. It errors right away.

Execution error (ClassCastException) at chapter6.core/eval1595 (form-init10872915734268438705.clj:1).
class chapter6.core$sum cannot be cast to class java.util.concurrent.Future (chapter6.core$sum is in unnamed module of loader cloju-re.lang.DynamicClassLoader @7c650722; java.util.concurrent.Future is in module java.base of loader 'bootstrap')

I'm new. I know nothing of "bootstrap" or "module" or... What am I doing wrong? Thank you in advance. BTW, is there a "...From The Ground Up" Answer Key for the Exercises?

标签: intellij-ideaclojurejava.util.concurrentcursive

解决方案


做了:

(deref (sum 0 1e7))

您的函数仅在调用时返回延迟。在(deref sum)中,没有任何东西调用它(事实上,如果调用它,您永远不会提供参数值将是强制性的。相反,您尝试取消引用函数sum本身,这是非法的,因为函数不是延迟。


推荐阅读