Skip to content

Instantly share code, notes, and snippets.

@leonoel leonoel/goto.clj
Last active Mar 15, 2019

What would you like to do?
CL's tagbody in clojure
(ns goto)
(defmacro tagbody [& forms]
(let [start (gensym)]
(loop [binds []
point start
forms forms]
(let [[body [jump & forms]] (split-with (complement symbol?) forms)
binds (conj binds `(~point [] ~@body ~jump))]
(if jump
(recur binds jump forms)
`(letfn ~binds
(loop [curr# ~start]
(when curr#
(try (curr#)
(catch Exception e#
(or (-> e# ex-data ::point) (throw e#)))))))))))))
(defn go [point]
(throw (ex-info "Illegal jump." {::point point})))
(let [val (atom nil)]
(reset! val 1)
(go point-a)
(swap! val + 16)
(swap! val + 4)
(go point-b)
(swap! val + 32)
(swap! val + 2)
(go point-c)
(swap! val + 64)
(swap! val + 8))
(defn f2 [flag escape]
(if flag (escape) 2))
(defn f1 [flag]
(let [n (atom 1)]
(reset! n (f2 flag #(go out)))
(prn @n))))
(f1 false)
(f1 true))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.