Search code examples
clojure

About the source of ->>


I was browsing the source of clojure.core:

(defmacro ->>
  [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)))

On line 7, why not just

(with-meta `(~@form  ~x) (meta form))

Solution

  • That's almost equivalent, but not quite. Consider what happens if form is (incorrectly) (). As written, this error is caught at compile time because it's illegal to evaluate (nil x). With your proposed simplification, the error would be noticed at runtime, or perhaps never at all if x happens to be a function of no arguments.

    Leaving aside correctness, it's also better for readability, since it emphasizes that the first of the form will be called, with the rest as arguments. It's also a nicer symmetry with the implementation of ->.