Clojure ships with a macro that threads the first expression through the rest. It’s called the threading operator and sometimes thrush operator. For some people, especially people with no background in Lisps, this may improve readability. It is quite common in Clojure but not seen in other Lisps so far.

Usage in Clojure

The thrush or threading operators of Clojure, ->> and ->, let one chain functions together. For example,

    (->> (seq accounts)
         (filter #(= (:type %) 'savings))
         (map :balance)
         (apply +))

expands to

    (apply +
      (map :balance
        (filter #(= (:type %) 'savings)
          (seq accounts))))

It’s analogous to the Unix pipeline operator.

EmacsLisp Implementation

The following macros implement the threading operators in Emacs Lisp.

    (defmacro ->> (&rest body)
      (let ((result (pop body)))
        (dolist (form body result)
          (setq result (append form (list result))))))
    (defmacro -> (&rest body)
      (let ((result (pop body)))
        (dolist (form body result)
          (setq result (append (list (car form) result)
                               (cdr form))))))

Note: good idea ! Another implementation here (look for “trush”), ported more or less directly from the Clojure macro. Like the original, it works on examples like this :

    (-> 25 sqrt (* 2)) ;; sqrt is replaced by (sqrt) while expanding the -> macro

You’ll find unit tests for it here (again, look for “trush”). Note: this implementation is for my own use, and not intended for distribution as it will polute your namespace.

External links


Please note, that several people at the EmacsWiki disagree that such functions from other lisps belong here. At least unless they come packaged as a nice library, like cl.el. These Clojure operators are often referred to as the Thrush, but that is a false analogy.