“ - >”之间的区别和“ - >>”在Clojure

时间:2014-08-23 04:44:45

标签: macros clojure

->->>之间有什么区别:

user> (macroexpand-1 '(->> 1 a b c))
;; => (c (b (a 1)))
user> (macroexpand-1 '(-> 1 a b c))
;; => (c (b (a 1)))

让我们看一下源代码:

user> (clojure.repl/source ->)
(defmacro ->
  "Threads the expr through the forms. Inserts x as the
  second item in the first form, making a list of it if it is not a
  list already. If there are more forms, inserts the first form as the
  second item in second form, etc."
  {:added "1.0"}
  [x & forms]
  (loop [x x, forms forms]
    (if forms
      (let [form (first forms)
            threaded (if (seq? form)
                       (with-meta `(~(first form) ~x ~@(next form))
                                   (meta form))
                       (list form x))]
        (recur threaded (next forms)))
      x)))
;; => nil

user> (clojure.repl/source ->>)
(defmacro ->>
  "Threads the expr through the forms. Inserts x as the
  last item in the first form, making a list of it if it is not a
  list already. If there are more forms, inserts the first form as the
  last item in second form, etc."
  {:added "1.1"}
  [x & forms]
  (loop [x x, forms forms]
    (if forms
      (let [form (first forms)
            threaded (if (seq? form)
                       (with-meta `(~(first form) ~@(next form) ~x)
                                   (meta form))
                       (list form x))]
        (recur threaded (next forms)))
      x)))
;; => nil

(缩进是我的。)

所以,->比较旧,但它们看起来很相似......重复的原因是什么?

1 个答案:

答案 0 :(得分:3)

在处理带有进一步参数的线程表单时,这两个宏是不同的。试试这些尺寸:

(macroexpand '(->> 1 (a b) (c d e) (f g h i)))
(macroexpand '(-> 1 (a b) (c d e) (f g h i)))