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?
There may be some confusion here from the different usages of the term "symbol" in Common Lisp and in Clojure. In Common Lisp, a "symbol" is a location in memory, a place where data can be stored. The "value" of a symbol is the data stored at that location in memory. In Clojure, a "symbol" is just a name.
Most Clojure code consists primarily of pure functions (no side effects), so invoking with the same inputs yields the same output. defn defines a named function: ;; name params body ;; ----- ------ ------------------- (defn greet [name] (str "Hello, " name) )
def is a special form that associates a symbol (x) in the current namespace with a value (7). This linkage is called a var . In most actual Clojure code, vars should refer to either a constant value or a function, but it's common to define and re-define them for convenience when working at the REPL.
List is a structure used to store a collection of data items. In Clojure, the List implements the ISeq interface. Lists are created in Clojure by using the list function.
->>
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 ...".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With