Created
April 25, 2021 13:09
-
-
Save bsless/c96d29df2037f728cf731f0848d6e1ab to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;; As originally seen and improved on https://gist.github.com/holyjak/578571a134ce90526e6907436e91014a | |
(import '[clojure.lang Box]) | |
(defmacro as | |
[tag sym] | |
(let [tag (if (class? tag) (.getName ^Class tag) (str tag))] | |
`(with-meta ~sym {:tag ~tag}))) | |
(definline box! | |
[v] | |
`(Box. ~v)) | |
(definline unbox! | |
[^Box b] | |
`(.-val ~(as Box b))) | |
(definline bset! | |
[^Box b v] | |
`(set! (. ~(as Box b) val) ~v)) | |
(defn bswap! | |
{:inline-arities #{2 3 4 5 6} | |
:inline (fn [b f & args] `(bset! ~b (~f (unbox! ~b) ~@args)))} | |
([^Box b f] (bset! b (f (unbox! b)))) | |
([^Box b f x] (bset! b (f (unbox! b) x))) | |
([^Box b f x y] (bset! b (f (unbox! b) x y))) | |
([^Box b f x y z] (bset! b (f (unbox! b) x y z))) | |
([^Box b f x y z & args] (bset! b (apply f (unbox! b) x y z args)))) | |
(defn with-state | |
([trf f] | |
(with-state trf f nil)) | |
([trf f init] | |
(with-state identity trf f init)) | |
([txf trf f init] | |
(let [state (box! init) | |
tf (txf trf)] | |
(fn [in] | |
(let [old (unbox! state)] | |
(bswap! state tf in) | |
(f old in)))))) | |
(defn right [x y] y) | |
(sequence (filter (with-state right not=)) [1 2 2 2 3 4 4 5]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment