Side effects are not implemented without separation

From clojure to the brave and the true:

(defmacro enqueue
  [q concurrent-promise-name & work]
  (let [concurrent (butlast work)
        serialized (last work)]
    `(let [~concurrent-promise-name (promise)]
       (future (deliver ~concurrent-promise-name (do ~@concurrent)))
       (deref ~q)
       ~serialized
       ~concurrent-promise-name)))
(defmacro wait
  "Sleep `timeout` seconds before evaluating body"
  [timeout & body]
  `(do (Thread/sleep ~timeout) ~@body))
(time @(-> (future (wait 200 (println "'Ello, gov'na!")))
           (enqueue saying (wait 400 "Pip pip!") (println @saying))
           (enqueue saying (wait 100 "Cheerio!") (println @saying))))

If I comment on the line (deref ~q), then only "Cheerio!" printed. Why do I need here to get other side effects?

+4
source share
1 answer

If you comment out (deref ~q), the code passed with qwill never be evaluated, so nested futures will not appear.

Macroexpansion:

(macroexpand '(-> (future (wait 200 (println "'Ello, gov'na!")))
                  (enqueue saying (wait 400 "Pip pip!") (println @saying))
                  (enqueue saying (wait 100 "Cheerio!") (println @saying))))
;;-> ....
(clojure.pprint/pp)

(let*
 [saying (clojure.core/promise)]
 (clojure.core/future
   (clojure.core/deliver saying (do (wait 100 "Cheerio!"))))
 ;; no code ended up here...
 (println @saying)
 saying)
+3
source

Source: https://habr.com/ru/post/1589288/


All Articles