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?
Make it:
(deref (sum 0 1e7))
Your function only returns a delay when it's called. In (deref sum)
, nothing calls it (and, indeed, you never provide argument values would would be mandatory to include were it called). Rather, you try to deref the function sum
itself, which is illegal, because a function is not a delay.