13

I am learning Clojure, and I came across this example:

  (defn people-in-scenes [scenes]
     (->> scenes
         (map :subject)
         (interpose ", ")
         (reduce str)))

What does ->> do exactly?

0

3 Answers 3

14

->> is the "thread-last" macro. It evaluates one form and passes it as the last argument into the next form.

Your code is the equivalent of:

(reduce str (interpose ", " (map :subject scenes)))

Or, to see it a different way:

(reduce str
            (interpose ", "
                            (map :subject scenes)))

When reading clojure code, one almost has to do so from the "inside out" or from the "bottom up." The threading macros allow you to read code in what some would say is a more logical order. "Take something, first do this to it, next do that, next ...".

0
3

I've found helpful to read Clojure cheatsheet (and ClojureScript cheatsheet). These have lists of all common functions in the language. Of course there are lots of other functions in additional libraries.

See also -> which passes function as a second argument into the next form.

1

The following produce identical results

(->> 10
    (range)
    (filter odd?)
    (map #(* 2 %))
    (reduce +))

The first is written as do this then this then that. The second is read left to right as "sum the doubled odd numbers less than 10".

(reduce + (map #(* 2 %) (filter odd? (range 10))))

If you're coming from javascript or C#, the first example reads like linq or dot-chaining in javascript.

range(10).filter(odd)
         .map(x => x * 2)
         .reduce((a,b) => a + b)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.