Skip to content

Instantly share code, notes, and snippets.

@keisukefukuda
Created August 4, 2015 01:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keisukefukuda/53a1207e4af2fa7a434b to your computer and use it in GitHub Desktop.
Save keisukefukuda/53a1207e4af2fa7a434b to your computer and use it in GitHub Desktop.
Creating custom vector [ver.1]
(ns samples.core)
(deftype MyVec [contents]
clojure.lang.Associative
(entryAt [_ key]
(let [v (.entryAt contents key)]
(if (future? v)
@v
v)))
(assoc [_ key, val]
(MyVec. (.assoc contents key val)))
clojure.lang.IPersistentStack
(peek [_] (.peek contents))
(pop [_] (MyVec. (.pop contents)))
clojure.lang.Reversible
(rseq [_]
(.rseq contents)) ;; Todo
clojure.lang.Indexed
(nth [_ i]
(let [v (.nth contents i)]
(if (future? v) @v v)))
(nth [_ i not-found]
(let [v (.nth contents i not-found)]
(if (future? v) @v v)))
clojure.lang.IPersistentCollection
(count [_]
(.count contents))
(empty [_]
(.empty contents))
(equiv [_ o]
(and (isa? (class o) MyVec)
(.equiv contents (:contents o))))
clojure.lang.ILookup
(valAt [_ k]
(let [v (.valAt contents k)]
(if (future? v)
@v
v)))
(valAt [_ k not-found]
(let [v (.valAt contents k not-found)]
(if (future? v)
@v
v)))
clojure.lang.IPersistentVector
(assocN [_ i val]
(MyVec. (.assocN contents i val)))
(cons [_ o]
(MyVec. (.cons contents o)))
clojure.lang.Sequential)
(defn heavy-computation [a]
(println "doing somewhat heavy computation")
a)
(defn -main [& args]
(let [v (MyVec. [:a
(future :b)
:c
(future (heavy-computation :d))])]
(println (get v 0))
(println (get v 1))
(println (get v 2))
(println (get v 3))))
=> doing somewhat heavy computation
:a
:b
:c
:d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment