Fixing doto to be API compatible with Clojure's doto

This commit is contained in:
Matthew Wampler-Doty 2014-04-21 12:35:56 -07:00
parent f4b67e8bd8
commit 834b0019a7
3 changed files with 24 additions and 21 deletions

View File

@ -563,23 +563,21 @@ del
doto doto
---- ----
`doto` macro is used to make repetitive calls to an object easy. Following `doto` macro is used to make a sequence of method calls for an object easy.
example demonstrates this.
.. code-block:: clj
=> (doto [] (.append 1) (.append 2) .reverse)
[2 1]
.. code-block:: clj .. code-block:: clj
=> (setv collection []) => (setv collection [])
=> (doto collection (.append 1) (.append 2)) => (.append collection 1)
=> (.append collection 2)
=> (.reverse collection)
=> collection => collection
[1 2] [2 1]
.. code-block:: clj
=> (setv collection [])
=> (.append 1 collection)
=> (.append 2 collection)
=> collection
[1 2]
eval eval
---- ----

View File

@ -128,14 +128,15 @@
(defmacro doto [form &rest expressions] (defmacro doto [form &rest expressions]
(setv expressions (iter expressions)) "Performs a sequence of potentially mutating actions on an initial object, returning the resulting object after the sequence is performed"
(defn build-form [form expression] (setv f (gensym))
`(~(first expression) ~form ~@(rest expression))) (defn build-form [expression]
(setv result `()) (if (isinstance expression HyExpression)
(for* [expression expressions] `(~(first expression) ~f ~@(rest expression))
(.append result (build-form form expression))) `(~expression ~f)))
`(do ~@result)) `(let [[~f ~form]]
~@(map build-form expressions)
~f))
(defmacro ->> [head &rest rest] (defmacro ->> [head &rest rest]
;; TODO: fix the docstring by someone who understands this ;; TODO: fix the docstring by someone who understands this

View File

@ -483,5 +483,9 @@
"NATIVE: testing doto macro" "NATIVE: testing doto macro"
(setv collection []) (setv collection [])
(doto collection (.append 1) (.append 2) (.append 3)) (doto collection (.append 1) (.append 2) (.append 3))
(assert-equal collection [1 2 3])) (assert-equal collection [1 2 3])
(setv res (doto (set) (.add 2) (.add 1)))
(assert-equal res (set [1 2]))
(setv res (doto [] (.append 1) (.append 2) .reverse))
(assert-equal res [2 1]))