Skip to content

Instantly share code, notes, and snippets.

@mbuczko
Last active October 23, 2020 20:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbuczko/0f25d36915e9cb0680046f15784e7a67 to your computer and use it in GitHub Desktop.
Save mbuczko/0f25d36915e9cb0680046f15784e7a67 to your computer and use it in GitHub Desktop.
clojure / parallel-let
(defn remote-req [result]
(Thread/sleep 1000)
result)
(defmacro plet [bindings & body]
(let [bents (partition 2 (destructure bindings))
smap (into {} (map (fn [[b _]]
[b `(deref ~b)])
bents))
bindings (vec (mapcat (fn [[b v]]
[b `(future ~(postwalk-replace smap v))])
bents))]
`(let ~bindings
~@(postwalk-replace smap body))))
(time
(let [{:keys [a]} (remote-req {:a 1 :x 2})
b (remote-req 1)
c (+ a b)
d (remote-req 1)
e (remote-req 1)
f (+ d e)]
(+ c f)))
;; "Elapsed time: 4007.60237 msecs"
(time
(plet [{:keys [a]} (remote-req {:a 1 :x 2})
b (remote-req 1)
c (+ a b)
d (remote-req 1)
e (remote-req 1)
f (+ d e)]
(+ c f)))
;; "Elapsed time: 1003.733416 msecs"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment