Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About the source of ->>

Tags:

clojure

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))
like image 682
damonh Avatar asked Jan 24 '17 15:01

damonh


1 Answers

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 ->.

like image 137
amalloy Avatar answered Nov 09 '22 21:11

amalloy