Mahmud Adam
Mahmud Adam

Reputation: 3579

What does ->> mean in Clojure?

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?

Upvotes: 15

Views: 6329

Answers (3)

nathan rogers
nathan rogers

Reputation: 300

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)

Upvotes: 2

KettuJKL
KettuJKL

Reputation: 272

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.

Upvotes: 3

Josh
Josh

Reputation: 4806

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

Upvotes: 15

Related Questions